/**
 * Seed built-in extraction tasks into Cosmos DB on service startup.
 * Idempotent — uses upsert so safe to call on every boot.
 */

import { upsertTask } from './repository.js';
import { DEFAULT_PRODUCT_ID } from '../../lib/product-config.js';
import type { ExtractionTaskDoc } from './types.js';

/**
 * Built-in task definitions.
 * These match the Python task_registry.py definitions exactly.
 */
const BUILTIN_TASKS: Omit<ExtractionTaskDoc, '_ts' | '_etag'>[] = [
  {
    id: 'transcript-extraction',
    name: 'Transcript Extraction',
    description: 'Extract structured entities from meeting transcripts and voice notes.',
    prompt:
      'Extract action items, decisions, questions, deadlines, people, and topics ' +
      'from the following transcript. Each extraction should be verbatim text from ' +
      'the source with the appropriate classification.',
    classes: ['action_item', 'decision', 'question', 'deadline', 'person', 'topic'],
    examples: [
      {
        text: 'John said we need to ship the feature by Friday. Sarah agreed to handle the testing.',
        extractions: [
          { extraction_class: 'deadline', extraction_text: 'ship the feature by Friday' },
          { extraction_class: 'person', extraction_text: 'John' },
          { extraction_class: 'person', extraction_text: 'Sarah' },
          {
            extraction_class: 'action_item',
            extraction_text: 'Sarah agreed to handle the testing',
          },
          {
            extraction_class: 'decision',
            extraction_text: 'we need to ship the feature by Friday',
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
  {
    id: 'triage',
    name: 'MindLyst Triage',
    description:
      'Extract topics, entities, actions, emotions, and brain routing signals from user captures.',
    prompt:
      'Analyze the following user capture and extract: topics, named entities, ' +
      'action items, emotional signals, date references, and brain routing signals. ' +
      'Brain signals should include which brain (work, home, money, health, global) ' +
      'the content belongs to with a confidence score.',
    classes: ['topic', 'entity', 'action', 'emotion', 'date_reference', 'brain_signal'],
    examples: [
      {
        text: "Remind me to call the dentist tomorrow about my appointment. I'm stressed about the cost.",
        extractions: [
          { extraction_class: 'action', extraction_text: 'call the dentist tomorrow' },
          { extraction_class: 'date_reference', extraction_text: 'tomorrow' },
          {
            extraction_class: 'emotion',
            extraction_text: 'stressed about the cost',
            attributes: { valence: 'negative' },
          },
          {
            extraction_class: 'brain_signal',
            extraction_text: 'dentist',
            attributes: { brain: 'health', confidence: '0.9' },
          },
          {
            extraction_class: 'brain_signal',
            extraction_text: 'cost',
            attributes: { brain: 'money', confidence: '0.6' },
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
  {
    id: 'memory-insight',
    name: 'Memory Insight Extraction',
    description:
      'Extract patterns, recurring themes, relationships, and milestones from accumulated brain memories.',
    prompt:
      'Analyze the following collection of memory items and extract: recurring patterns, ' +
      'themes, relationships between items, and milestones.',
    classes: ['pattern', 'recurring_theme', 'relationship', 'milestone'],
    examples: [
      {
        text: 'Item 1: Skipped gym again. Item 2: Feeling tired at work. Item 3: Had coffee at 4pm.',
        extractions: [
          {
            extraction_class: 'pattern',
            extraction_text: 'Skipped gym again',
            attributes: { frequency: 'recurring' },
          },
          {
            extraction_class: 'relationship',
            extraction_text: 'Feeling tired at work',
            attributes: { related_to: 'Skipped gym again' },
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
  {
    id: 'reflection-enrichment',
    name: 'Reflection Enrichment',
    description:
      'Extract emotional states, accomplishments, concerns, and goal progress from journal-style text.',
    prompt:
      'Analyze the following reflection or journal entry and extract: emotional states, ' +
      'accomplishments, concerns, and goal progress indicators.',
    classes: ['emotional_state', 'accomplishment', 'concern', 'goal_progress'],
    examples: [
      {
        text: "Good day overall. Finally finished the proposal I've been putting off. Still worried about the budget review next week.",
        extractions: [
          {
            extraction_class: 'emotional_state',
            extraction_text: 'Good day overall',
            attributes: { valence: 'positive' },
          },
          { extraction_class: 'accomplishment', extraction_text: 'finished the proposal' },
          {
            extraction_class: 'concern',
            extraction_text: 'worried about the budget review next week',
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
  {
    id: 'bug-report-extraction',
    name: 'Bug Report Extraction',
    description: 'Extract structured fields from bug report submissions.',
    prompt:
      'Extract steps to reproduce, expected behavior, actual behavior, affected component, ' +
      'and severity from the following bug report.',
    classes: [
      'steps_to_reproduce',
      'expected_behavior',
      'actual_behavior',
      'affected_component',
      'severity',
    ],
    examples: [
      {
        text: 'When I click the save button on the settings page, nothing happens. It should save my preferences. This is a critical issue affecting all users.',
        extractions: [
          {
            extraction_class: 'steps_to_reproduce',
            extraction_text: 'click the save button on the settings page',
          },
          { extraction_class: 'actual_behavior', extraction_text: 'nothing happens' },
          {
            extraction_class: 'expected_behavior',
            extraction_text: 'should save my preferences',
          },
          { extraction_class: 'affected_component', extraction_text: 'settings page' },
          {
            extraction_class: 'severity',
            extraction_text: 'critical issue affecting all users',
            attributes: { level: 'critical' },
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
  {
    id: 'timer-parse',
    name: 'Timer Natural Language Parse',
    description:
      'Extract structured timer parameters from natural language input for ChronoMind. ' +
      'Parses time references, durations, urgency hints, labels, recurrence, and travel context.',
    prompt:
      'Parse the following natural language timer request and extract: absolute or relative time references, ' +
      'durations, urgency hints (critical/important/standard/gentle/passive), a concise label, ' +
      'recurrence patterns (daily/weekly/weekdays), and any travel-time context. ' +
      'Return each extraction with its class and the verbatim text that triggered it.',
    classes: ['time', 'duration', 'urgency_hint', 'label', 'recurrence', 'travel_context'],
    examples: [
      {
        text: 'Set a critical alarm for my dentist next Tuesday at 2pm with 1 hour warning and 30 min travel time',
        extractions: [
          { extraction_class: 'time', extraction_text: 'next Tuesday at 2pm' },
          {
            extraction_class: 'urgency_hint',
            extraction_text: 'critical',
            attributes: { level: 'critical' },
          },
          { extraction_class: 'label', extraction_text: 'dentist' },
          {
            extraction_class: 'duration',
            extraction_text: '1 hour warning',
            attributes: { minutes: '60', type: 'cascade_warning' },
          },
          {
            extraction_class: 'travel_context',
            extraction_text: '30 min travel time',
            attributes: { minutes: '30' },
          },
        ],
      },
      {
        text: 'Remind me every weekday at 9am to take vitamins',
        extractions: [
          { extraction_class: 'time', extraction_text: '9am' },
          {
            extraction_class: 'recurrence',
            extraction_text: 'every weekday',
            attributes: { pattern: 'weekdays' },
          },
          { extraction_class: 'label', extraction_text: 'take vitamins' },
        ],
      },
      {
        text: '25 minute focus session for writing',
        extractions: [
          {
            extraction_class: 'duration',
            extraction_text: '25 minute',
            attributes: { minutes: '25', type: 'countdown' },
          },
          { extraction_class: 'label', extraction_text: 'writing' },
          {
            extraction_class: 'urgency_hint',
            extraction_text: 'focus session',
            attributes: { level: 'standard', timer_type: 'pomodoro' },
          },
        ],
      },
    ],
    defaultModelId: 'gemini-2.5-flash',
    builtIn: true,
    productId: DEFAULT_PRODUCT_ID,
  },
];

/**
 * Seed all built-in tasks. Idempotent via upsert.
 * Call this during service startup.
 */
export async function seedBuiltInTasks(log?: {
  info: (...args: unknown[]) => void;
}): Promise<void> {
  let seeded = 0;
  for (const task of BUILTIN_TASKS) {
    const now = new Date().toISOString();
    await upsertTask({
      ...task,
      createdAt: task.createdAt || now,
      updatedAt: now,
    });
    seeded++;
  }
  log?.info({ seeded, total: BUILTIN_TASKS.length }, 'built-in extraction tasks seeded');
}
