// QAF-Vergleich-Export (Demo-067 E, KAR-984) — Markdown. Same content/order
// as qaf-docx.ts's buildQafComparisonCopilotDocx, consuming the exact same
// QafComparisonDocxInput contract and rendering the same already-computed
// QafComparisonResult fields — only the markup changes. `fmtDelta` is
// duplicated 1:1 from qaf-docx.ts rather than imported (task scope:
// "Wiederverwendung statt Refactor", DOCX builders stay untouched — see
// assessment-md.ts's header for the same call on a different helper).
//
// Pure function of its inputs — no Supabase/DB access, no async work.

import { buildAiInstructionBlock } from './ai-instruction-block'
import { formatNumberDe, formatPercentDe } from './docx-shared'
import { joinMdBlocks, mdBold, mdH1, mdH2, mdKvTable, mdTable, mdTitle, renderAiInstructionBlockMd } from './md-shared'
import type { QafComparisonDocxInput } from './qaf-docx'
import { exportProfileStampLineDe } from '@/lib/qaf-differences'

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 function buildQafComparisonCopilotMd(input: QafComparisonDocxInput): string {
  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 blocks: string[] = [
    mdTitle('QAF-Vergleich-Export'),
    mdBold(`Sachnummer ${partLabel} — ${c.altRef.fileName} (ALT) vs. ${c.neuRef.fileName} (NEU)`),
    // Loop 12: profilübergreifender Versions-Stempel — sichtbar im Kopf.
    exportProfileStampLineDe('copilot_md'),
    ...renderAiInstructionBlockMd(aiBlock),

    mdH1('Steckbrief'),
    mdKvTable([
      ['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],
    ]),

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

  // ── Struktur-Änderungen (Neu_Entfallen sheet equivalent) ────────────────
  blocks.push(mdH1('Struktur-Änderungen'))
  const { new: newSteps, removed: removedSteps, possible: possibleSteps } = c.structureChanges
  if (newSteps.length === 0 && removedSteps.length === 0 && possibleSteps.length === 0) {
    blocks.push('Keine strukturellen Änderungen zwischen ALT und NEU.')
  } else {
    blocks.push(
      mdTable(
        ['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),
        ],
      ),
    )
  }

  // ── Top-Treiber (Top_Treiber_Prozess sheet equivalent) ──────────────────
  blocks.push(mdH1('Top-Kostentreiber'))
  if (c.rootCause.topAbsoluteDrivers.length === 0 && c.rootCause.topRelativeDrivers.length === 0) {
    blocks.push('Keine signifikanten Treiber ermittelt.')
  } else {
    blocks.push(
      mdTable(
        ['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),
        ],
      ),
    )
  }

  // ── Feld-Diffs je Prozessschritt (Fertigungskosten_Vergleich sheet
  // equivalent) — only matched steps, same guard the DOCX/XLSX exports use. ─
  blocks.push(mdH1('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) {
    blocks.push('Keine Feld-Diffs verfügbar (keine gematchten Prozessschritte).')
  } else {
    blocks.push(mdTable(['Prozessschritt', 'Feld', 'ALT', 'NEU', 'Delta', 'Status'], diffRows))
  }

  // ── Plausibilitätscheck ──────────────────────────────────────────────────
  blocks.push(mdH1('Plausibilitätscheck'))
  if (c.plausibility.length === 0) {
    blocks.push('Keine Plausibilitäts-Auffälligkeiten.')
  } else {
    blocks.push(
      mdTable(
        ['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) {
    blocks.push(mdH2('Hinweis'))
    blocks.push(
      `${c.matchReviewCount} Prozessschritt-Zuordnung(en) wurden automatisch vorgeschlagen und sind manuell zu prüfen (siehe Anwendung).`,
    )
  }

  return joinMdBlocks(blocks)
}
