import { describe, expect, it } from 'vitest'
import JSZip from 'jszip'
import type { ValueStreamMap } from '@/lib/vsm-types'
import { buildWertstromCopilotDocx } from '../internal/wertstrom-docx'

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',
  }
}

async function documentXml(buf: Buffer): Promise<string> {
  const zip = await JSZip.loadAsync(buf)
  const entry = zip.file('word/document.xml')
  if (!entry) throw new Error('word/document.xml missing from generated DOCX')
  return entry.async('string')
}

describe('buildWertstromCopilotDocx', () => {
  it('produces a real DOCX with the AI-instruction block, KPIs, and process-step/connection tables', async () => {
    const buf = await buildWertstromCopilotDocx({ vsm: vsm(), taktTimeSec: 60, isDemo: false, generatedAtLabel: '19.07.2026, 10:00' })
    expect(Buffer.isBuffer(buf)).toBe(true)

    const xml = await documentXml(buf)
    expect(xml).toContain('Wertstrom-Export')
    expect(xml).toContain('Wertstrom Musterwerk Linie 3')
    expect(xml).toContain('Schweißen')
    expect(xml).toContain('Puffer')
    expect(xml).toContain('Value Stream Map')
    expect(xml).not.toContain('Demo-Hinweis')
  })

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

  it('handles an empty Wertstrom (no nodes/connections) without throwing', async () => {
    const empty: ValueStreamMap = { ...vsm(), nodes: [], connections: [] }
    const buf = await buildWertstromCopilotDocx({ vsm: empty, taktTimeSec: null, isDemo: false, generatedAtLabel: 'x' })
    const xml = await documentXml(buf)
    expect(xml).toContain('Keine Prozessschritte erfasst.')
    expect(xml).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', async () => {
    const buf = await buildWertstromCopilotDocx({ vsm: vsm(), taktTimeSec: 60, isDemo: false, generatedAtLabel: 'x' })
    const xml = await documentXml(buf)
    expect(xml).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(xml).toContain('Diese Datei enthält eine SupplierPulse-Wertstromanalyse.')
  })

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

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

  // C5-Fix (Wertstrom P7 fix-round): "Kennzahlen" and "Management-Analyse"
  // used to compute the engpass via two DIFFERENT models (legacy
  // findBottleneckId vs. computeBottleneckV2) — a mixed process+machine map
  // (the exact finding repro) used to show a contradiction in the SAME
  // document: "Engpass: —" in Kennzahlen next to a real, confident engpass
  // sentence in Management-Analyse. Both now agree.
  it('Kennzahlen and Management-Analyse agree on the same v2 bottleneck for a mixed process+machine map', async () => {
    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 buf = await buildWertstromCopilotDocx({ vsm: mixed, taktTimeSec: 80, isDemo: false, generatedAtLabel: 'x' })
    const xml = await documentXml(buf)
    expect(xml).toContain('MaschineB')
    expect(xml).not.toContain('weniger als 2 Prozess-Nodes')
    expect(xml).toContain('MaschineB ist der primäre Engpass')
  })
})
