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

export interface QATestCase {
  type: string
  description: string
  automatizable: string
  tool: string
}


export interface HUQAPlan {
  huTitle: string
  huId: string
  acceptanceCriteria: string[]
  testCases: QATestCase[]
  manualSteps: string[]
  criticalTests: string[]
}

export async function generateQAPlan(huTitle: string, huDescription: string, acceptanceCriteria: string): Promise<HUQAPlan> {
  const userContent = `HU: ${huTitle}\nDescripción: ${huDescription}\nCriterios: ${acceptanceCriteria}`
  const systemPrompt = await getPrompt('qa')
  const content = await callAI(
    [{ role: 'system', content: systemPrompt }, { role: 'user', content: userContent }],
    0.3, 4096,
  )
  try {
    const jsonStr = extractJSON(content)
    const result: Omit<HUQAPlan, 'huTitle' | 'huId'> = JSON.parse(jsonStr)
    return { huTitle, huId: '', ...result }
  } catch (e) {
    console.error('[Alpha] Failed to parse QA plan. Raw:', content)
    throw new Error(`Error generando plan QA para: ${huTitle}`)
  }
}

export async function saveQAPlan(projectId: number, huId: string, huTitle: string, plan: HUQAPlan) {
  await db.table('qa_plans').put({
    id: `${projectId}-${huId}`, projectId, huId, huTitle,
    plan: JSON.stringify(plan),
    createdAt: new Date().toISOString(),
  })
}

export async function getQAPlans(projectId: number) {
  return db.table('qa_plans').where('projectId').equals(projectId).toArray()
}

export async function generateAndSavePlan(projectId: number, huId: string, huTitle: string, huDescription: string, acceptanceCriteria: string): Promise<HUQAPlan> {
  const plan = await generateQAPlan(huTitle, huDescription, acceptanceCriteria)
  plan.huId = huId
  await saveQAPlan(projectId, huId, huTitle, plan)
  return plan
}

function extractJSON(text: string): string {
  try { JSON.parse(text); return text } catch {}
  const block = text.match(/```(?:json)?\s*([\s\S]*?)```/)
  if (block) { try { JSON.parse(block[1].trim()); return block[1].trim() } catch {} }
  const first = text.indexOf('{')
  const last = text.lastIndexOf('}')
  if (first !== -1 && last > first) { const c = text.slice(first, last + 1); try { JSON.parse(c); return c } catch {} }
  return text
}
