import { getSessionsByProject, getSessionSummary, getProjectState, type SessionRecord, type ProjectStateRecord } from '@/services/transcriptions-db'

/**
 * Genera el markdown del proyecto completamente desde la BD.
 * No recibe datos de sesión directos — los obtiene de las tablas.
 */
export async function generateMasterDoc(projectId: number, projectName: string): Promise<string> {
  const state = await getProjectState(projectId)
  const sessions = await getSessionsByProject(projectId)

  const block1 = buildBlock1(state, projectName, sessions.length)
  const block2 = await buildBlock2(sessions)

  return `${block1}\n\n${block2}\n`
}

function buildBlock1(
  state: ProjectStateRecord | undefined,
  projectName: string,
  sessionCount: number,
): string {
  const now = new Date().toISOString().slice(0, 16).replace('T', ' ')

  const objectives = safeParse<string[]>(state?.objectives, [])
  const tasks = safeParse<{ description: string; origin: string; priority: string; status?: string }[]>(state?.tasks, [])
  const commitments = safeParse<{ description: string; responsible: string; dueDate: string; status: string }[]>(state?.commitments, [])
  const summary = state?.summary || 'Sin resumen disponible'

  const objectivesMd = objectives.map(o => `- [ ] ${o}`).join('\n')
  const tasksMd = tasks.map((t, i) => `| ${i + 1} | [${t.status === 'completada' ? 'x' : ' '}] ${t.description} | ${t.origin} | ${t.priority} |`).join('\n')
  const commitmentsMd = commitments.map(c =>
    `| ${c.description} | ${c.responsible} | ${c.dueDate} | ${c.status === 'Cumplido' ? '✅' : '⏳'} | — |`
  ).join('\n')
  const milestonesMd = commitments
    .filter(c => c.dueDate && c.status !== 'Cumplido')
    .map(c => `- **${c.dueDate}**: ${c.description} (_${c.responsible}_)`)
    .join('\n')

  return `# 📋 ${projectName} — Resumen Ejecutivo

> ⚠️ Última actualización: ${now}

---

## 🎯 Resumen Ejecutivo
${summary}

## 🎯 Objetivos
${objectivesMd || '_Sin objetivos registrados_'}

## 📝 Tareas Pendientes
| # | Tarea | Origen | Prioridad |
|---|-------|--------|-----------|
${tasksMd || '_Sin tareas pendientes_'}

## ✅ Compromisos
| Compromiso | Responsable | Fecha límite | Estado | Notas |
|------------|-------------|--------------|--------|-------|
${commitmentsMd || '_Sin compromisos_'}

## 📅 Próximos Hitos
${milestonesMd || '_Sin hitos próximos_'}

## 📊 Métricas de Seguimiento
- Sesiones registradas: ${sessionCount}
- Tareas pendientes: ${tasks.filter(t => t.status !== 'completada').length}
- Compromisos cumplidos: ${commitments.filter(c => c.status === 'Cumplido').length}/${commitments.length}`
}

async function buildBlock2(sessions: SessionRecord[]): Promise<string> {
  if (sessions.length === 0) return '## 📜 Registro de Sesiones\n\n_Sin sesiones registradas_'

  const parts: string[] = ['---\n\n## 📜 Registro Completo de Sesiones']

  for (const session of sessions) {
    const summary = await getSessionSummary(session.id!)
    const objectives = safeParse<{ text: string; isNew: boolean }[]>(summary?.objectives, [])
    const tasks = safeParse<{ description: string; origin: string; priority: string }[]>(summary?.tasks, [])
    const commitments = safeParse<{ description: string; responsible: string; dueDate: string; status: string }[]>(summary?.commitments, [])
    const decisions = safeParse<string[]>(summary?.decisions, [])
    const keyPoints = safeParse<string[]>(summary?.keyPoints, [])

    const entry = `---

## 📍 Sesión: ${session.date} — ${session.title}

**Archivo fuente:** \`${session.fileName}\`

### Resumen de la sesión
${summary?.summary || '_Sin resumen disponible_'}

### Objetivos de esta sesión
${objectives.map(o => `- ${o.isNew ? '🆕 ' : ''}${o.text}`).join('\n') || '_Ninguno_'}

### Tareas identificadas en esta sesión
${tasks.map(t => `- [ ] ${t.description} (_${t.priority}_)`).join('\n') || '_Ninguna_'}

### Compromisos de esta sesión
${commitments.map(c => `- ${c.description} → ${c.responsible} (${c.dueDate}) [${c.status}]`).join('\n') || '_Ninguno_'}

### Decisiones tomadas
${decisions.map(d => `- ${d}`).join('\n') || '_Ninguna_'}

### Puntos clave
${keyPoints.map(k => `- ${k}`).join('\n') || '_Ninguno_'}

### Transcripción completa

\`\`\`
${session.rawText}
\`\`\``

    parts.push(entry)
  }

  return parts.join('\n')
}

function safeParse<T>(json: string | undefined | null, fallback: T): T {
  if (!json) return fallback
  try { return JSON.parse(json) as T } catch { return fallback }
}
