// QAF-Vergleich-Export (Demo-067 C, KAR-982) — DOCX. Renders the SAME
// QafComparisonResult the 8-sheet XLSX reference export
// (lib/qaf-differences/internal/export.ts's buildQafExportWorkbook) is built
// from — no re-implementation of the diff engine, only a narrative rendering
// of already-computed fields (rootCause.managementSummary, structureChanges,
// stepComparisons[].fieldDiffs, plausibility). Field selection/labels mirror
// that export's sheet columns (Fertigungskosten_Vergleich, Neu_Entfallen,
// Top_Treiber_Prozess, Plausibilitätscheck) for consistency with the
// existing export.
//
// Pure function of its inputs — the caller (server action) rehydrates the
// comparison via lib/qaf-differences's rehydrateExportInput (same call the
// XLSX export makes) and passes the resulting QafComparisonResult in.

import { exportProfileStampLineDe } from '@/lib/qaf-differences'
import type { Paragraph, Table } from 'docx'
import type { QafComparisonResult } from '@/lib/qaf-differences'
import { buildAiInstructionBlock } from './ai-instruction-block'
import {
  bodyText,
  buildDocument,
  dataTable,
  docTitle,
  formatNumberDe,
  formatPercentDe,
  heading1,
  heading2,
  kvTable,
  packDocumentToBuffer,
  renderAiInstructionBlock,
  spacer,
} from './docx-shared'

export interface QafComparisonDocxInput {
  comparison: QafComparisonResult
  isDemo: boolean
  generatedAtLabel: string
}

function fmtDelta(deltaAbsolute: number | null, deltaPercent: number | null): string {
  if (deltaAbsolute === null) return '—'
  const sign = deltaAbsolute > 0 ? '+' : ''
  const pct = deltaPercent !== null ? ` (${sign}${formatPercentDe(deltaPercent)})` : ''
  return `${sign}${formatNumberDe(deltaAbsolute)}${pct}`
}

export async function buildQafComparisonCopilotDocx(input: QafComparisonDocxInput): Promise<Buffer> {
  const { comparison: c, generatedAtLabel } = input
  const partLabel = c.partNumber ?? '—'

  const aiBlock = buildAiInstructionBlock({
    exportTitle: 'QAF-Vergleich-Export',
    aboutText:
      'Dieses Dokument ist der Export eines QAF-Vergleichs — der Feld-für-Feld-Gegenüberstellung ' +
      'zweier Qualitäts-Anforderungs-Formulare (ALT vs. NEU) für dieselbe Sachnummer. Es enthält das ' +
      'automatisch erzeugte Management-Fazit, Struktur-Änderungen, die größten Kostentreiber und die ' +
      'vollständige Feld-Diff-Tabelle je Prozessschritt.',
    usageHints: [
      'Nutze das Management-Fazit als Ausgangspunkt und vertiefe es mit den Top-Treibern und der Feld-Diff-Tabelle.',
      'Erkläre Kostenanstiege (rot/Anstieg) und -senkungen (grün/Senkung) getrennt und ordne sie den betroffenen Prozessschritten zu.',
      'Prüfe die Plausibilitätscheck-Tabelle auf Einträge mit Severity "kritisch", bevor du eine abschließende Bewertung formulierst.',
    ],
    isDemo: input.isDemo,
  })

  const children: (Paragraph | Table)[] = [
    docTitle('QAF-Vergleich-Export'),
    bodyText(`Sachnummer ${partLabel} — ${c.altRef.fileName} (ALT) vs. ${c.neuRef.fileName} (NEU)`, { bold: true }),
    // Loop 12: profilübergreifender Versions-Stempel — sichtbar im Kopf.
    bodyText(exportProfileStampLineDe('copilot_docx')),
    spacer(),
    ...renderAiInstructionBlock(aiBlock),

    heading1('Steckbrief'),
    kvTable([
      ['Sachnummer', partLabel],
      ['Datei ALT', c.altRef.fileName],
      ['Datei NEU', c.neuRef.fileName],
      ['Regel-Modus', c.ruleEnforcement],
      ['Manuell zu prüfende Zuordnungen', String(c.matchReviewCount)],
      ['Erzeugt am', generatedAtLabel],
    ]),

    heading1('Management-Fazit'),
    bodyText(c.rootCause.managementSummary || 'Kein automatisches Fazit verfügbar.'),
    spacer(),
  ]

  // ── Struktur-Änderungen (Neu_Entfallen sheet equivalent) ────────────────
  children.push(heading1('Struktur-Änderungen'))
  const { new: newSteps, removed: removedSteps, possible: possibleSteps } = c.structureChanges
  if (newSteps.length === 0 && removedSteps.length === 0 && possibleSteps.length === 0) {
    children.push(bodyText('Keine strukturellen Änderungen zwischen ALT und NEU.'))
  } else {
    children.push(
      dataTable(
        ['Art', 'Prozessschritt'],
        [
          ...newSteps.map((s) => ['neu', s] as const),
          ...removedSteps.map((s) => ['entfallen', s] as const),
          ...possibleSteps.map((s) => ['mögliche Umstrukturierung', s] as const),
        ],
      ),
    )
  }
  children.push(spacer())

  // ── Top-Treiber (Top_Treiber_Prozess sheet equivalent) ──────────────────
  children.push(heading1('Top-Kostentreiber'))
  if (c.rootCause.topAbsoluteDrivers.length === 0 && c.rootCause.topRelativeDrivers.length === 0) {
    children.push(bodyText('Keine signifikanten Treiber ermittelt.'))
  } else {
    children.push(
      dataTable(
        ['Treiber-Typ', 'Prozessschritt', 'Feld', 'Delta'],
        [
          ...c.rootCause.topAbsoluteDrivers.map((d) => ['absolut', d.stepLabel, String(d.field), fmtDelta(d.deltaAbsolute, d.deltaPercent)] as const),
          ...c.rootCause.topRelativeDrivers.map((d) => ['relativ', d.stepLabel, String(d.field), fmtDelta(d.deltaAbsolute, d.deltaPercent)] as const),
        ],
      ),
    )
  }
  children.push(spacer())

  // ── Feld-Diffs je Prozessschritt (Fertigungskosten_Vergleich sheet
  // equivalent) — only matched steps, same guard the XLSX export uses. ────
  children.push(heading1('Feld-Diffs je Prozessschritt'))
  const diffRows: Array<readonly [string, string, string, string, string, string]> = []
  for (const sc of c.stepComparisons) {
    if (sc.altIndex === null || sc.neuIndex === null) continue
    for (const d of sc.fieldDiffs) {
      diffRows.push([
        sc.stepLabel,
        String(d.field),
        formatNumberDe(d.altValue),
        formatNumberDe(d.neuValue),
        fmtDelta(d.deltaAbsolute, d.deltaPercent),
        d.status,
      ] as const)
    }
  }
  if (diffRows.length === 0) {
    children.push(bodyText('Keine Feld-Diffs verfügbar (keine gematchten Prozessschritte).'))
  } else {
    children.push(dataTable(['Prozessschritt', 'Feld', 'ALT', 'NEU', 'Delta', 'Status'], diffRows))
  }
  children.push(spacer())

  // ── Plausibilitätscheck ──────────────────────────────────────────────────
  children.push(heading1('Plausibilitätscheck'))
  if (c.plausibility.length === 0) {
    children.push(bodyText('Keine Plausibilitäts-Auffälligkeiten.'))
  } else {
    children.push(
      dataTable(
        ['Typ', 'Severity', 'Prozessschritt', 'Feld', 'Erklärung'],
        c.plausibility.map((i) => [i.type, i.severity, i.step ?? '—', i.field ?? '—', i.explanation] as const),
      ),
    )
  }

  if (c.matchReviewCount > 0) {
    children.push(spacer())
    children.push(heading2('Hinweis'))
    children.push(
      bodyText(
        `${c.matchReviewCount} Prozessschritt-Zuordnung(en) wurden automatisch vorgeschlagen und sind manuell zu prüfen (siehe Anwendung).`,
      ),
    )
  }

  const doc = buildDocument(`QAF-Vergleich-Export — ${partLabel}`, children)
  return packDocumentToBuffer(doc)
}
