import { callAI } from '@/services/ai'
import { getPrompt } from '@/services/prompts-db'

export interface SessionExtraction {
  sessionDate: string   // YYYY-MM-DD
  sessionTitle: string
  summary: string
  objectives: { text: string; isNew: boolean }[]
  pendingTasks: { description: string; origin: string; priority: string }[]
  commitments: { description: string; responsible: string; dueDate: string; status: string }[]
  decisions: string[]
  completedTasks: string[]
  keyPoints: string[]
}

export async function analyzeSession(
  transcription: string,
  projectName: string,
  signal?: AbortSignal
): Promise<SessionExtraction> {
  const userContent = `Proyecto: ${projectName}\n\nTranscripción:\n${transcription}`

  console.log(`[Alpha] Session analyze — project: ${projectName}, text: ${transcription.length} chars`)

  const systemPrompt = await getPrompt('session')
  const content = await callAI(
    [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userContent },
    ],
    0.3,
    4096,
    signal,
  )

  try {
    const jsonStr = extractJSON(content)
    const result: SessionExtraction = JSON.parse(jsonStr)
    console.log(`[Alpha] Session analysis complete — ${result.pendingTasks.length} tasks, ${result.decisions.length} decisions`)
    return result
  } catch (e) {
    console.error('[Alpha] Failed to parse session analysis. Raw response:', content)
    throw new Error('No se pudo parsear el análisis de la sesión')
  }
}

/**
 * Extrae el primer objeto JSON válido del texto.
 * Maneja markdown code blocks, texto antes/después, etc.
 */
function extractJSON(text: string): string {
  // 1. Intentar parse directo
  try { JSON.parse(text); return text } catch {}

  // 2. Extraer entre ```json y ```
  const jsonBlock = text.match(/```(?:json)?\s*([\s\S]*?)```/)
  if (jsonBlock) {
    const candidate = jsonBlock[1].trim()
    try { JSON.parse(candidate); return candidate } catch {}
  }

  // 3. Extraer entre { y } (first { to last })
  const firstBrace = text.indexOf('{')
  const lastBrace = text.lastIndexOf('}')
  if (firstBrace !== -1 && lastBrace > firstBrace) {
    const candidate = text.slice(firstBrace, lastBrace + 1)
    try { JSON.parse(candidate); return candidate } catch {}
  }

  // 4. Fallback: devolver el texto original (lanzará error en el caller)
  return text
}
