import { describe, expect, it } from 'vitest'
import type { ValueStreamMap } from '@/lib/vsm-types'
import { buildWertstromCopilotMd } from '../internal/wertstrom-md'

function vsm(): ValueStreamMap {
  return {
    id: 'vsm1',
    project_id: 'p1',
    title: 'Wertstrom Musterwerk Linie 3',
    description: 'Testbeschreibung',
    nodes: [
      { id: 'n1', type: 'process', x: 0, y: 0, name: 'Schweißen', cycleTimeSec: 45, isValueAdded: true, numWorkers: 2, machineType: 'Roboterzelle' },
      { id: 'n2', type: 'inventory', x: 100, y: 0, name: 'Puffer', waitTimeSec: 300 },
    ],
    connections: [{ id: 'c1', fromNodeId: 'n1', toNodeId: 'n2', label: 'Transport', transportTimeSec: 12, batchSize: 20 }],
    layout: {},
    created_by: 'u1',
    created_at: '2026-07-01T08:00:00Z',
    updated_at: '2026-07-01T08:00:00Z',
    is_demo: false,
    // Wertstrom P2 (KAR-878/KAR-986): required fields (DB NOT NULL DEFAULT
    // 'current' / nullable uuid) — this fixture is an ordinary Ist-map.
    parent_value_stream_id: null,
    scenario_kind: 'current',
  }
}

describe('buildWertstromCopilotMd', () => {
  it('produces Markdown with the AI-instruction block, KPIs, and process-step/connection tables', () => {
    const md = buildWertstromCopilotMd({ vsm: vsm(), taktTimeSec: 60, isDemo: false, generatedAtLabel: '19.07.2026, 10:00' })
    expect(typeof md).toBe('string')

    expect(md).toContain('# Wertstrom-Export')
    expect(md).toContain('## Hinweis für die KI-gestützte Weiterverarbeitung — Wertstrom-Export')
    expect(md).toContain('Wertstrom Musterwerk Linie 3')
    expect(md).toContain('Schweißen')
    expect(md).toContain('Puffer')
    // Glossary.
    expect(md).toContain('Value Stream Map')
    expect(md).toContain('| Begriff | Definition |')
    // Module core numbers/table headers.
    expect(md).toContain('## Kennzahlen')
    expect(md).toContain('VA-Quote')
    expect(md).toContain('| Name | Typ | Zykluszeit (s) | VA-Klasse | Maschinentyp | Mitarbeiter | Standort |')
    expect(md).not.toContain('Demo-Hinweis')
  })

  it('renders the fictional-data disclaimer only when isDemo is true', () => {
    const withDemo = buildWertstromCopilotMd({ vsm: vsm(), taktTimeSec: null, isDemo: true, generatedAtLabel: 'x' })
    const withoutDemo = buildWertstromCopilotMd({ vsm: vsm(), taktTimeSec: null, isDemo: false, generatedAtLabel: 'x' })
    expect(withDemo).toContain('Demo-Hinweis')
    expect(withoutDemo).not.toContain('Demo-Hinweis')
  })

  it('handles an empty Wertstrom (no nodes/connections) without throwing', () => {
    const empty: ValueStreamMap = { ...vsm(), nodes: [], connections: [] }
    const md = buildWertstromCopilotMd({ vsm: empty, taktTimeSec: null, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('Keine Prozessschritte erfasst.')
    expect(md).toContain('Keine Verbindungen erfasst.')
  })

  // Wertstrom P7 (A17, §19.3 Microsoft Copilot Export).
  it('includes the §19.3 instruction block verbatim (English original) + a German translation', () => {
    const md = buildWertstromCopilotMd({ vsm: vsm(), taktTimeSec: 60, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain(
      '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.',
    )
    expect(md).toContain('Diese Datei enthält eine SupplierPulse-Wertstromanalyse.')
  })

  it('includes a Management-Analyse section with the Business-Interpretation sentences', () => {
    const md = buildWertstromCopilotMd({ vsm: vsm(), taktTimeSec: 60, demandUnitsPerDay: 100, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('## Management-Analyse')
    expect(md).toContain('Der Kundenbedarf beträgt 100 Stück pro Tag.')
    expect(md).toContain('Der Kundentakt beträgt 60 Sekunden.')
  })

  it('includes an explicit Provenance-Übersicht (measured/planned/imported/calculated/assumed counts)', () => {
    const withProvenance: ValueStreamMap = { ...vsm(), nodes: [{ ...vsm().nodes[0], provenance: 'measured' }, vsm().nodes[1]] }
    const md = buildWertstromCopilotMd({ vsm: withProvenance, taktTimeSec: null, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('## Provenance-Übersicht')
    expect(md).toContain('Gemessen')
    expect(md).toContain('Ohne Herkunftsangabe')
  })

  // C5-Fix (Wertstrom P7 fix-round) — same repro as wertstrom-docx.test.ts's
  // sibling test (this module duplicates that one's structure 1:1).
  it('Kennzahlen and Management-Analyse agree on the same v2 bottleneck for a mixed process+machine map', () => {
    const mixed: ValueStreamMap = {
      ...vsm(),
      nodes: [
        { id: 'p1', type: 'process', x: 0, y: 0, name: 'ProzessA', cycleTimeSec: 100 },
        { id: 'm1', type: 'machine', x: 200, y: 0, name: 'MaschineB', cycleTimeSec: 90, oee: 40 },
      ],
      connections: [],
    }
    const md = buildWertstromCopilotMd({ vsm: mixed, taktTimeSec: 80, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('MaschineB')
    expect(md).not.toContain('weniger als 2 Prozess-Nodes')
    expect(md).toContain('MaschineB ist der primäre Engpass')
  })
})
