/**
 * AI infrastructure seed data — system-ai.
 * Seeds: ai_model_pricing (3 models), ai_global_config (singleton), ai_tier_quotas (4 tiers).
 */
import { and, eq, isNull } from 'drizzle-orm'
import type { Db } from '../client'
import {
  aiModelPricing,
  aiGlobalConfig,
  aiTierQuotas,
} from '../schema/ai'

// Default use-case system prompts
const DEFAULT_USE_CASE_PROMPTS: Record<string, string> = {
  expense_ocr:
    'You are an expert at extracting structured data from expense receipt images. Extract: merchant name, date, total amount, currency, tax amount, expense category. Return JSON only. Be precise with amounts.',
  expense_tax_eval:
    'You are an Israeli tax expert specializing in business expense deductibility. Evaluate the provided expense against the 8 IL tax deductibility categories. Return: {category, deductiblePercent, reasoning}. Be conservative and accurate.',
  task_autocreate:
    'You are a task extraction assistant. Given a message or email, extract actionable tasks. Return a JSON array of tasks with: title (concise), description (optional), priority (low/medium/high), dueDate (ISO date if mentioned). Extract only explicit tasks, not hypothetical ones.',
  ai_assistant:
    'You are a helpful business assistant for Zync, a business management platform. Help users with their business tasks, questions about invoices, expenses, projects, and time tracking. Be professional, concise, and accurate.',
  telegram_assistant:
    'You are a Telegram business assistant for Zync. Users interact with you via Telegram to manage their business. Keep responses concise for mobile. Support Hebrew and English. Route complex requests to the web app.',
  kb_suggest:
    'You are a knowledge base assistant. Given a support ticket or question, suggest relevant knowledge base articles and provide a draft response. Be helpful and accurate. Format article suggestions as a numbered list.',
  invoice_extract:
    'You are an invoice data extraction specialist. Extract all invoice fields from the provided document: invoice number, date, due date, vendor details, line items (description, quantity, unit price, total), subtotal, tax, total. Return structured JSON.',
}

/**
 * Seed AI model pricing with 3 default models.
 */
export async function seedAIModelPricing(db: Db): Promise<void> {
  const models = [
    {
      modelId: 'claude-3-5-haiku-20241022',
      provider: 'anthropic' as const,
      label: 'Claude 3.5 Haiku',
      inputCostPer1m: '0.800000',    // $0.80 per 1M input tokens
      outputCostPer1m: '4.000000',   // $4.00 per 1M output tokens
      isVisionCapable: true,
      active: true,
    },
    {
      modelId: 'gpt-4o',
      provider: 'openai' as const,
      label: 'GPT-4o',
      inputCostPer1m: '2.500000',    // $2.50 per 1M input tokens
      outputCostPer1m: '10.000000',  // $10.00 per 1M output tokens
      isVisionCapable: true,
      active: true,
    },
    {
      modelId: 'gemini-1.5-flash',
      provider: 'google' as const,
      label: 'Gemini 1.5 Flash',
      inputCostPer1m: '0.075000',    // $0.075 per 1M input tokens
      outputCostPer1m: '0.300000',   // $0.30 per 1M output tokens
      isVisionCapable: true,
      active: true,
    },
  ]

  for (const model of models) {
    await db
      .insert(aiModelPricing)
      .values(model)
      .onConflictDoNothing()
  }
}

/**
 * Seed the ai_global_config singleton.
 */
export async function seedAIGlobalConfig(db: Db): Promise<void> {
  await db
    .insert(aiGlobalConfig)
    .values({
      mainModelId: 'claude-3-5-haiku-20241022',
      backupModelIds: ['gpt-4o', 'gemini-1.5-flash'],
      useCasePrompts: DEFAULT_USE_CASE_PROMPTS,
    })
    .onConflictDoNothing()
}

/**
 * Seed per-tier quotas.
 * Freelancer: OCR-only use case, low token cap, no extras.
 * Business+: all use cases, configurable quota and extras.
 */
export async function seedAITierQuotas(db: Db): Promise<void> {
  const today = new Date().toISOString().slice(0, 10)

  const quotas = [
    {
      tier: 'freelancer',
      modelId: 'claude-3-5-haiku-20241022',
      monthlyTokens: 50_000,      // ~50 OCR calls worth
      extraAllowed: false,
      extraMaxUsd: null,
      effectiveFrom: today,
      effectiveTo: null,
    },
    {
      tier: 'business',
      modelId: 'claude-3-5-haiku-20241022',
      monthlyTokens: 2_000_000,   // 2M tokens/month
      extraAllowed: true,
      extraMaxUsd: '25.00',       // Up to $25 extra/month
      effectiveFrom: today,
      effectiveTo: null,
    },
    {
      tier: 'enterprise',
      modelId: 'claude-3-5-haiku-20241022',
      monthlyTokens: 10_000_000,  // 10M tokens/month
      extraAllowed: true,
      extraMaxUsd: '100.00',      // Up to $100 extra/month
      effectiveFrom: today,
      effectiveTo: null,
    },
    {
      tier: 'white_label',
      modelId: 'claude-3-5-haiku-20241022',
      monthlyTokens: 50_000_000,  // 50M tokens/month
      extraAllowed: true,
      extraMaxUsd: '500.00',      // Up to $500 extra/month
      effectiveFrom: today,
      effectiveTo: null,
    },
  ]

  for (const quota of quotas) {
    // Only insert if no current row exists for this tier
    const existing = await db
      .select()
      .from(aiTierQuotas)
      .where(and(eq(aiTierQuotas.tier, quota.tier), isNull(aiTierQuotas.effectiveTo)))
      .limit(1)

    if (existing.length === 0) {
      await db.insert(aiTierQuotas).values(quota)
    }
  }
}

/**
 * Run all AI seed operations in dependency order.
 */
export async function seedAI(db: Db): Promise<void> {
  console.log('[seed] Seeding AI model pricing…')
  await seedAIModelPricing(db)
  console.log('[seed] Seeding AI global config…')
  await seedAIGlobalConfig(db)
  console.log('[seed] Seeding AI tier quotas…')
  await seedAITierQuotas(db)
  console.log('[seed] AI seed complete.')
}
