import { describe, expect, it } from 'vitest'
import { DEFAULT_ENGINE_CONFIG, type QafComparisonResult } from '@/lib/qaf-differences'
import { buildQafComparisonCopilotMd } from '../internal/qaf-md'

function comparison(): QafComparisonResult {
  return {
    partNumber: '12345-AB',
    altRef: { id: 'file-alt', fileName: 'ALT_Angebot.xlsx', quotationDate: '2026-01-01' },
    neuRef: { id: 'file-neu', fileName: 'NEU_Aktuell.xlsx', quotationDate: '2026-06-01' },
    stepComparisons: [
      {
        altIndex: 0,
        neuIndex: 0,
        stepLabel: '10 Schweißen',
        match: {
          altIndex: 0,
          neuIndex: 0,
          matchStatus: 'safe_match',
          confidenceScore: 1,
          matchMethod: 'exact',
          matchedFields: [],
          conflictingFields: [],
          explanation: 'exakte Übereinstimmung',
          requiresReview: true,
        },
        fieldDiffs: [
          {
            field: 'fk',
            altValue: 10,
            neuValue: 12,
            deltaAbsolute: 2,
            deltaPercent: 0.2,
            deltaPercentagePoints: null,
            isPercentField: false,
            status: 'anstieg',
          },
        ],
        includedInDelta: true,
      },
    ],
    summaryDiffs: [],
    structureChanges: { new: ['20 Neuer Prozessschritt'], removed: [], possible: [] },
    plausibility: [
      {
        type: 'formel_geaendert',
        severity: 'pruefen',
        step: '10 Schweißen',
        field: 'fk',
        explanation: 'Formel wurde gegenüber ALT verändert.',
      },
    ],
    rootCause: {
      partNumber: '12345-AB',
      topAbsoluteDrivers: [{ stepLabel: '10 Schweißen', field: 'fk', deltaAbsolute: 2, deltaPercent: 0.2 }],
      topRelativeDrivers: [],
      structureChanges: { new: ['20 Neuer Prozessschritt'], removed: [], possible: [] },
      currencyEffect: false,
      managementSummary: 'Die Fertigungskosten steigen primär durch Prozessschritt 10 Schweißen.',
      requiresReviewNote: true,
    },
    matchReviewCount: 1,
    ruleEnforcement: 'warn',
    engineConfig: DEFAULT_ENGINE_CONFIG,
  }
}

describe('buildQafComparisonCopilotMd', () => {
  it('produces Markdown with the AI-instruction block, management summary, structure changes, and the field-diff table', () => {
    const md = buildQafComparisonCopilotMd({ comparison: comparison(), isDemo: false, generatedAtLabel: '19.07.2026, 10:00' })
    expect(typeof md).toBe('string')

    expect(md).toContain('# QAF-Vergleich-Export')
    expect(md).toContain('## Hinweis für die KI-gestützte Weiterverarbeitung — QAF-Vergleich-Export')
    expect(md).toContain('12345-AB')
    expect(md).toContain('ALT_Angebot.xlsx')
    expect(md).toContain('Die Fertigungskosten steigen primär durch Prozessschritt 10 Schweißen.')
    expect(md).toContain('20 Neuer Prozessschritt')
    expect(md).toContain('Formel wurde gegenüber ALT verändert.')
    // Glossary.
    expect(md).toContain('Qualitäts-Anforderungs-Formular')
    expect(md).toContain('| Begriff | Definition |')
    // Module core numbers/table headers.
    expect(md).toContain('| Prozessschritt | Feld | ALT | NEU | Delta | Status |')
    expect(md).toContain('| --- | --- | --- | --- | --- | --- |')
    expect(md).toContain('+2,00')
    expect(md).not.toContain('Demo-Hinweis')
  })

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

  it('renders "keine Feld-Diffs" when no step comparisons matched', () => {
    const unmatched: QafComparisonResult = {
      ...comparison(),
      stepComparisons: [{ ...comparison().stepComparisons[0], altIndex: null, neuIndex: null }],
    }
    const md = buildQafComparisonCopilotMd({ comparison: unmatched, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('Keine Feld-Diffs verfügbar')
  })

  it('renders "keine strukturellen Änderungen"/"keine Treiber"/"keine Auffälligkeiten" for an otherwise-empty comparison', () => {
    const flat: QafComparisonResult = {
      ...comparison(),
      structureChanges: { new: [], removed: [], possible: [] },
      plausibility: [],
      rootCause: {
        ...comparison().rootCause,
        topAbsoluteDrivers: [],
        topRelativeDrivers: [],
        structureChanges: { new: [], removed: [], possible: [] },
      },
      matchReviewCount: 0,
    }
    const md = buildQafComparisonCopilotMd({ comparison: flat, isDemo: false, generatedAtLabel: 'x' })
    expect(md).toContain('Keine strukturellen Änderungen zwischen ALT und NEU.')
    expect(md).toContain('Keine signifikanten Treiber ermittelt.')
    expect(md).toContain('Keine Plausibilitäts-Auffälligkeiten.')
  })
})
