import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'
import { requireSupabaseAuth } from '@/integrations/supabase/auth-middleware'

const schema = z.object({
  category: z.enum(['receivables', 'payment', 'reconciliation', 'customer']),
  description: z.string().trim().min(15).max(3000),
})

const SYSTEM = `You are DueWise's receivables and payments advisor for finance teams. Treat monetary amounts as USD unless the user explicitly states another currency.
The user describes an accounts receivable, payment, reconciliation or customer-payment issue.
Respond in plain, professional language using exactly these markdown sections:
## What is likely happening
(2-4 sentences explaining probable causes)
## Recommended next actions
(3-6 numbered, concrete steps a finance team can take today)
## What to check in DueWise
(2-4 bullets referencing invoices, payments, reconciliation queue, customer history or cash-flow views)
## Risk to watch
(1-2 sentences)
Do not invent figures, customer names or facts not supplied. If details are missing, say what information would sharpen the diagnosis. Keep the total under 350 words. This is guidance, not legal or accounting advice.`

export const analyzeIssue = createServerFn({ method: 'POST' })
  .middleware([requireSupabaseAuth])
  .inputValidator((x) => schema.parse(x))
  .handler(async ({ data }) => {
    const apiKey = process.env['LOVABLE_API_KEY']
    if (!apiKey) return { ok: false as const, error: 'The AI service is not configured yet.' }
    const { createOpenAI } = await import('@ai-sdk/openai')
    const { streamText } = await import('ai')
    const provider = createOpenAI({
      baseURL: 'https://ai.gateway.lovable.dev/v1',
      apiKey,
      headers: { 'Lovable-API-Key': apiKey, 'X-Lovable-AIG-SDK': 'vercel-ai-sdk' },
    })
    try {
      let streamError: unknown
      const result = streamText({
        model: provider.responses('openai/gpt-6-astra'),
        system: SYSTEM,
        prompt: `Issue type: ${data.category}\n\nDescription:\n${data.description}`,
        onError: ({ error }) => { streamError = error },
        providerOptions: {
          openai: {
            forceReasoning: true,
            reasoningEffort: 'medium',
            reasoningSummary: 'auto',
            store: false,
            include: ['reasoning.encrypted_content'],
          },
        },
      })
      const text = await result.text
      if (streamError || !text.trim()) throw streamError ?? new Error('empty')
      return { ok: true as const, text }
    } catch (e: any) {
      const status = e?.statusCode ?? e?.status ?? e?.cause?.statusCode
      console.error('analyzeIssue failed', status, e?.message)
      const error =
        status === 429 ? 'The advisor is receiving many requests. Please try again in a minute.'
        : status === 402 ? 'AI credits for this workspace have run out. Add credits in Settings → Plans & credits.'
        : status === 403 ? 'AI access is currently restricted for this workspace.'
        : 'The advisor could not complete this analysis. Please try again.'
      return { ok: false as const, error }
    }
  })
