// Wertstrom-Export (Demo-067 E, KAR-984) — Markdown. Same content/order as
// wertstrom-docx.ts's buildWertstromCopilotDocx, consuming the exact same
// WertstromDocxInput contract and the same derived-metrics functions
// (components/wertstrom/vsm-metrics.ts) — only the markup changes.
// NODE_TYPE_LABEL/nodeValueAddedLabel/secLabel/rollupRows are duplicated 1:1
// from wertstrom-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 different helpers).
//
// Pure function of its inputs — no Supabase/DB access, no async work.
//
// Wertstrom P7 (§19.3): same 3 additive sections as wertstrom-docx.ts
// (Copilot-Anweisung, Management-Analyse, Provenance-Übersicht).
// COPILOT_INSTRUCTION_BLOCK_*/provenanceCounts are duplicated 1:1 from
// wertstrom-docx.ts (same "duplicated, not cross-imported" convention this
// file's own header already established above for NODE_TYPE_LABEL/etc. —
// wertstrom-docx.ts pulls in the `docx` package; this file deliberately does
// not).

import type { ValueProvenance, VsmNode } from '@/lib/vsm-types'
import {
  computeCostPerUnitRollup,
  computeScrapCostRollup,
  computeSetupTimeSum,
  computeTimeline,
  computeTransportTimeSum,
  computeVaClassBreakdown,
  computeWaitTimeSum,
  type CostRollup,
  type NodeTimeSum,
} from '@/components/wertstrom/vsm-metrics'
import { PROVENANCE_LABELS } from '@/components/wertstrom/vsm-config'
import { computeBottleneckV2, computeManagementAnalysis } from '@/lib/vsm-engine'
import { buildAiInstructionBlock } from './ai-instruction-block'
import { formatNumberDe } from './docx-shared'
import { joinMdBlocks, mdBold, mdH1, mdH3, mdItalic, mdKvTable, mdTable, mdTitle, renderAiInstructionBlockMd } from './md-shared'
import type { WertstromDocxInput } from './wertstrom-docx'

const NODE_TYPE_LABEL: Record<VsmNode['type'], string> = {
  process: 'Prozess',
  machine: 'Maschine',
  inventory: 'Bestand',
  transport: 'Transport',
  customer: 'Kunde',
  supplier: 'Lieferant',
  timevalue: 'Zeitwertlinie',
}

function nodeValueAddedLabel(n: VsmNode): string {
  if (n.vaClass) {
    return { va: 'wertschöpfend (VA)', nnva: 'notwendig, nicht wertschöpfend (NNVA)', nva: 'nicht wertschöpfend (NVA)', unknown: 'ungeklärt' }[n.vaClass]
  }
  return n.isValueAdded ? 'wertschöpfend (VA)' : '—'
}

function secLabel(sum: NodeTimeSum): string {
  return sum.totalSec === null ? 'keine Datenbasis' : `${formatNumberDe(sum.totalSec, 0)} s (${sum.nodeCount} Node(s))`
}

function rollupRows(rollup: CostRollup): ReadonlyArray<readonly [string, string]> {
  if (rollup.buckets.length === 0) return [['—', 'keine Datenbasis']]
  return rollup.buckets.map((b) => [b.currency, `${formatNumberDe(b.total)} (${b.nodeCount} Node(s))`] as const)
}

// Wertstrom P7 (§19.3, wörtlich) — duplicated 1:1 from wertstrom-docx.ts, see
// this file's own header comment for why.
const COPILOT_INSTRUCTION_BLOCK_EN =
  'This file contains a SupplierPulse value stream analysis. Analyze the current state, future state, process data, inventories, material flows, information flows, bottlenecks, risks and measures as one connected operational system. Create a management summary, prioritized measure plan, decision document or presentation structure. Clearly distinguish measured, planned, imported, calculated and assumed values.'
const COPILOT_INSTRUCTION_BLOCK_DE =
  'Diese Datei enthält eine SupplierPulse-Wertstromanalyse. Analysieren Sie Ist-Zustand, Soll-Zustand, Prozessdaten, Bestände, Materialflüsse, Informationsflüsse, Engpässe, Risiken und Maßnahmen als ein zusammenhängendes operatives System. Erstellen Sie eine Management-Zusammenfassung, einen priorisierten Maßnahmenplan, ein Entscheidungsdokument oder eine Präsentationsstruktur. Unterscheiden Sie klar zwischen gemessenen, geplanten, importierten, berechneten und angenommenen Werten.'

const PROVENANCE_ORDER: ValueProvenance[] = ['measured', 'planned', 'calculated', 'imported', 'assumed']

function provenanceCounts(nodes: VsmNode[]): ReadonlyArray<readonly [string, string]> {
  const counts = new Map<ValueProvenance, number>()
  let unknown = 0
  for (const n of nodes) {
    if (n.provenance) counts.set(n.provenance, (counts.get(n.provenance) ?? 0) + 1)
    else unknown++
  }
  const rows: Array<readonly [string, string]> = PROVENANCE_ORDER.map((p) => [PROVENANCE_LABELS[p], String(counts.get(p) ?? 0)] as const)
  rows.push(['Ohne Herkunftsangabe', String(unknown)])
  return rows
}

export function buildWertstromCopilotMd(input: WertstromDocxInput): string {
  const { vsm, taktTimeSec, isDemo, generatedAtLabel, demandUnitsPerDay, shiftModel } = input
  const nodes = vsm.nodes
  const nodeNameById = new Map(nodes.map((n) => [n.id, n.name || '(unbenannt)']))

  const timeline = computeTimeline(nodes)
  const vaBreakdown = computeVaClassBreakdown(nodes)
  const setupSum = computeSetupTimeSum(nodes)
  const waitSum = computeWaitTimeSum(nodes)
  const transportSum = computeTransportTimeSum(nodes)
  const costRollup = computeCostPerUnitRollup(nodes)
  const scrapRollup = computeScrapCostRollup(nodes)

  const capacityOverridesByNodeId: Record<string, { availabilityPct?: number }> = {}
  for (const n of nodes) {
    if ((n.type === 'process' || n.type === 'machine') && n.availabilityPct != null) capacityOverridesByNodeId[n.id] = { availabilityPct: n.availabilityPct }
  }
  // P7 fix-round Grundsatz-Entscheidung "v2 überall, wo 'Engpass'
  // draufsteht" — see wertstrom-docx.ts's identical fix for the full
  // rationale (this file duplicates that module's structure 1:1, same
  // "duplicated, not cross-imported" convention this file's own header
  // already documents).
  const bottleneck = computeBottleneckV2(nodes, taktTimeSec, capacityOverridesByNodeId)
  const bottleneckName = bottleneck.primary?.nodeName ?? null
  const managementAnalysis = computeManagementAnalysis(nodes, vsm.connections, { taktTimeSec, demandUnitsPerDay, shiftModel, capacityOverridesByNodeId })

  const aiBlock = buildAiInstructionBlock({
    exportTitle: 'Wertstrom-Export',
    aboutText:
      'Dieses Dokument ist der Export eines Wertstroms (VSM) — der visuellen Darstellung des Material- ' +
      'und Informationsflusses durch ein Produktionssystem. Es enthält die Prozessschritte, ihre ' +
      'Verbindungen sowie abgeleitete Kennzahlen (VA-Quote, Rüst-/Warte-/Transportzeit-Summen, ' +
      'Kosten-Rollup je Währung) exakt so, wie sie auch im Wertstrom-Editor berechnet werden.',
    usageHints: [
      'Nutze die VA-Quote und den Engpass (Bottleneck) als Einstieg für eine Verschwendungs-Analyse.',
      'Bei mehreren Währungs-Buckets im Kosten-Rollup: niemals über Buckets hinweg addieren, sondern getrennt bewerten.',
      'Prozessschritte ohne Zykluszeit oder ohne VA-Klassifizierung explizit als Datenlücke benennen, nicht schätzen.',
    ],
    isDemo,
  })

  const blocks: string[] = [
    mdTitle('Wertstrom-Export'),
    mdBold(vsm.title),
    ...renderAiInstructionBlockMd(aiBlock),

    mdH1('Copilot-Anweisung (§19.3)'),
    COPILOT_INSTRUCTION_BLOCK_DE,
    mdH3('Original (Englisch)'),
    mdItalic(COPILOT_INSTRUCTION_BLOCK_EN),

    mdH1('Steckbrief'),
    mdKvTable([
      ['Titel', vsm.title],
      ['Beschreibung', vsm.description ?? '—'],
      ['Prozessschritte', String(nodes.length)],
      ['Verbindungen', String(vsm.connections.length)],
      ['Kundentakt', taktTimeSec !== null ? `${formatNumberDe(taktTimeSec, 0)} s` : '— (kein verknüpftes Projekt mit Kundentakt)'],
      ['Erzeugt am', generatedAtLabel],
    ]),

    mdH1('Kennzahlen'),
    mdKvTable([
      ['VA-Quote', `${vaBreakdown.vaRatioPct} % (${formatNumberDe(timeline.va, 0)} s wertschöpfend von ${formatNumberDe(timeline.total, 0)} s gesamt)`],
      ['Rüstzeit-Summe', secLabel(setupSum)],
      ['Wartezeit-Summe', secLabel(waitSum)],
      ['Transportzeit-Summe (Node-Ebene)', secLabel(transportSum)],
      ['Engpass (Bottleneck)', bottleneckName ?? '— (kein Kundentakt oder zu wenig Kapazitätsdaten für eine Engpass-Berechnung)'],
    ]),

    mdH1('VA-Klassen-Verteilung'),
    mdTable(
      ['Klasse', 'Sekunden', 'Anzahl Nodes'],
      [
        ['VA (gemeldet)', formatNumberDe(vaBreakdown.va.seconds, 0), String(vaBreakdown.va.nodeCount)],
        ['NNVA', formatNumberDe(vaBreakdown.nnva.seconds, 0), String(vaBreakdown.nnva.nodeCount)],
        ['NVA', formatNumberDe(vaBreakdown.nva.seconds, 0), String(vaBreakdown.nva.nodeCount)],
        ['Ungeklärt', formatNumberDe(vaBreakdown.unknown.seconds, 0), String(vaBreakdown.unknown.nodeCount)],
        ['VA (abgeleitet aus isValueAdded)', formatNumberDe(vaBreakdown.derivedVa.seconds, 0), String(vaBreakdown.derivedVa.nodeCount)],
        ['Nicht-VA (abgeleitet)', formatNumberDe(vaBreakdown.derivedNonVa.seconds, 0), String(vaBreakdown.derivedNonVa.nodeCount)],
      ],
    ),

    mdH1('Kosten-Rollup je Währung (BW)'),
    mdKvTable(rollupRows(costRollup)),
    mdH1('Ausschuss-Kosten-Rollup je Angebotswährung (AW)'),
    mdKvTable(rollupRows(scrapRollup)),

    mdH1('Management-Analyse'),
    ...managementAnalysis.statements.map((s) => `${s.text} (Konfidenz: ${s.confidence})`),
  ]

  blocks.push(mdH1('Prozessschritte'))
  if (nodes.length === 0) {
    blocks.push('Keine Prozessschritte erfasst.')
  } else {
    blocks.push(
      mdTable(
        ['Name', 'Typ', 'Zykluszeit (s)', 'VA-Klasse', 'Maschinentyp', 'Mitarbeiter', 'Standort'],
        nodes.map((n) => [
          n.name || '(unbenannt)',
          NODE_TYPE_LABEL[n.type] ?? n.type,
          n.cycleTimeSec !== undefined ? formatNumberDe(n.cycleTimeSec, 1) : '—',
          nodeValueAddedLabel(n),
          n.machineType ?? '—',
          n.numWorkers !== undefined ? String(n.numWorkers) : '—',
          n.location ?? '—',
        ]),
      ),
    )
  }

  blocks.push(mdH1('Verbindungen'))
  if (vsm.connections.length === 0) {
    blocks.push('Keine Verbindungen erfasst.')
  } else {
    blocks.push(
      mdTable(
        ['Von', 'Nach', 'Label', 'Transportzeit (s)', 'Losgröße'],
        vsm.connections.map((conn) => [
          nodeNameById.get(conn.fromNodeId) ?? conn.fromNodeId,
          nodeNameById.get(conn.toNodeId) ?? conn.toNodeId,
          conn.label ?? '—',
          conn.transportTimeSec !== undefined ? formatNumberDe(conn.transportTimeSec, 1) : '—',
          conn.batchSize !== undefined ? String(conn.batchSize) : '—',
        ]),
      ),
    )
  }

  blocks.push(mdH1('Provenance-Übersicht'))
  blocks.push(mdKvTable(provenanceCounts(nodes)))

  return joinMdBlocks(blocks)
}
