// Gesamtprojekt-Export (Demo-067 C, KAR-982) — DOCX. Combines
// Projekt-Stammdaten + Workshop/Agenda + Maßnahmen + Kurzfassungen der
// Modul-Stände (FA/QAF/Wertstrom/LSC) into one narrative document. Pure
// function of its inputs — the caller (server action) loads the project row,
// agendas (lib/agenda/server-queries's loadProjectAgendas), workshop_actions,
// and the per-module rollups, and maps them into ProjectExportInput.

import type { Paragraph, Table } from 'docx'
import { buildAiInstructionBlock } from './ai-instruction-block'
import {
  bodyText,
  buildDocument,
  dataTable,
  docTitle,
  heading1,
  heading2,
  heading3,
  kvTable,
  packDocumentToBuffer,
  renderAiInstructionBlock,
  spacer,
} from './docx-shared'
import { formatDeDate, stammdatenEntries, workshopActionHeaders, workshopActionRow } from './project-content'
import type { ProjectExportInput } from './project-types'

export async function buildProjectCopilotDocx(input: ProjectExportInput): Promise<Buffer> {
  const { stammdaten, agendas, workshopActions, moduleSummaries, generatedAtLabel } = input

  const aiBlock = buildAiInstructionBlock({
    exportTitle: 'Gesamtprojekt-Export',
    aboutText:
      'Dieses Dokument ist der Gesamtprojekt-Export — eine Zusammenfassung eines Lieferantenentwicklungs-' +
      'Projekts über alle Module hinweg: Projekt-Stammdaten, Workshop-Agenda, offene und abgeschlossene ' +
      'Maßnahmen sowie Kurzfassungen des Stands in den Fachmodulen (Fabrikanalyse/QAF-Vergleich/Wertstrom/LSC). ' +
      'Die Modul-Abschnitte sind bewusst kurz gehalten — für die vollständigen Daten eines einzelnen Moduls ' +
      'gibt es dessen eigenen Copilot-Export.',
    usageHints: [
      'Erstelle eine Projekt-Statusübersicht: Stammdaten, offene Maßnahmen nach Priorität, Modul-Fortschritt.',
      'Bei der Agenda: fasse Ziel und Ablauf der Werksbesuch-Tage in wenigen Sätzen zusammen.',
      'Wenn ein Modul-Abschnitt "keine Daten" zeigt, das nicht als Ergebnis interpretieren, sondern als "noch nicht erfasst".',
    ],
    isDemo: stammdaten.isDemo,
  })

  const children: (Paragraph | Table)[] = [
    docTitle('Gesamtprojekt-Export'),
    bodyText(`${stammdaten.supplierName}${stammdaten.plantLocation ? ` — ${stammdaten.plantLocation}` : ''}`, { bold: true }),
    spacer(),
    ...renderAiInstructionBlock(aiBlock),

    heading1('Stammdaten'),
    kvTable([...stammdatenEntries(stammdaten), ['Erzeugt am', generatedAtLabel]]),
    spacer(),
  ]

  // ── Workshop / Agenda ────────────────────────────────────────────────────
  children.push(heading1('Workshop / Agenda'))
  if (agendas.length === 0) {
    children.push(bodyText('Keine Agenda angelegt.'))
  } else {
    for (const agenda of agendas) {
      children.push(heading2(`${agenda.title} (${agenda.language.toUpperCase()}, ${agenda.status})`))
      if (agenda.days.length === 0) {
        children.push(bodyText('Keine Tage geplant.'))
        continue
      }
      for (const day of agenda.days) {
        children.push(heading3(`${day.title ?? 'Tag'}${day.date ? ` — ${formatDeDate(day.date)}` : ''}`))
        if (day.items.length === 0) {
          children.push(bodyText('Keine Programmpunkte.'))
          continue
        }
        children.push(
          dataTable(
            ['Zeit', 'Titel', 'Verantwortlich', 'Ort'],
            day.items.map((item) => [
              [item.startTime, item.endTime].filter(Boolean).join('–') || '—',
              item.title,
              item.responsible ?? '—',
              item.location ?? '—',
            ]),
          ),
        )
      }
    }
  }
  children.push(spacer())

  // ── Maßnahmen ────────────────────────────────────────────────────────────
  children.push(heading1('Maßnahmen'))
  if (workshopActions.length === 0) {
    children.push(bodyText('Keine Maßnahmen erfasst.'))
  } else {
    children.push(dataTable(workshopActionHeaders(), workshopActions.map((a) => workshopActionRow(a))))
  }
  children.push(spacer())

  // ── Kurzfassungen der Modul-Stände ───────────────────────────────────────
  children.push(heading1('Modul-Stände (Kurzfassung)'))
  if (moduleSummaries.length === 0) {
    children.push(bodyText('Keine Modul-Daten für dieses Projekt.'))
  } else {
    for (const m of moduleSummaries) {
      children.push(heading2(`${m.label} — ${m.countLabel}`))
      if (m.items.length === 0) {
        children.push(bodyText('Keine Einträge.'))
      } else {
        for (const item of m.items) children.push(bodyText(item))
      }
    }
  }

  const doc = buildDocument(`Gesamtprojekt-Export — ${stammdaten.supplierName}`, children)
  return packDocumentToBuffer(doc)
}
