// Gesamtprojekt-Export (Demo-067 E, KAR-984) — Markdown. Same content/order
// as project-docx.ts's buildProjectCopilotDocx, consuming the exact same
// ProjectExportInput contract — only the markup changes. Unlike the other
// three MD builders, no helper duplication is needed here: project-
// content.ts already exists specifically to be shared across formats
// (its own header: "reused by both project-docx.ts (docx tables) and
// project-xlsx.ts (exceljs worksheets), so the two formats never drift") —
// this builder is simply a third consumer of that existing, already-format-
// agnostic file.
//
// Pure function of its inputs — no Supabase/DB access, no async work.

import { buildAiInstructionBlock } from './ai-instruction-block'
import { joinMdBlocks, mdBold, mdH1, mdH2, mdH3, mdKvTable, mdTable, mdTitle, renderAiInstructionBlockMd } from './md-shared'
import { formatDeDate, stammdatenEntries, workshopActionHeaders, workshopActionRow } from './project-content'
import type { ProjectExportInput } from './project-types'

export function buildProjectCopilotMd(input: ProjectExportInput): string {
  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 blocks: string[] = [
    mdTitle('Gesamtprojekt-Export'),
    mdBold(`${stammdaten.supplierName}${stammdaten.plantLocation ? ` — ${stammdaten.plantLocation}` : ''}`),
    ...renderAiInstructionBlockMd(aiBlock),

    mdH1('Stammdaten'),
    mdKvTable([...stammdatenEntries(stammdaten), ['Erzeugt am', generatedAtLabel]]),
  ]

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

  // ── Maßnahmen ────────────────────────────────────────────────────────────
  blocks.push(mdH1('Maßnahmen'))
  if (workshopActions.length === 0) {
    blocks.push('Keine Maßnahmen erfasst.')
  } else {
    blocks.push(mdTable(workshopActionHeaders(), workshopActions.map((a) => workshopActionRow(a))))
  }

  // ── Kurzfassungen der Modul-Stände ───────────────────────────────────────
  blocks.push(mdH1('Modul-Stände (Kurzfassung)'))
  if (moduleSummaries.length === 0) {
    blocks.push('Keine Modul-Daten für dieses Projekt.')
  } else {
    for (const m of moduleSummaries) {
      blocks.push(mdH2(`${m.label} — ${m.countLabel}`))
      if (m.items.length === 0) {
        blocks.push('Keine Einträge.')
      } else {
        blocks.push(m.items.join('\n'))
      }
    }
  }

  return joinMdBlocks(blocks)
}
