// KAR-949 — Multi-QAF XLSX export real-file regression (env-gated).
//
// Same discipline as summary-totals-differ.real-files.test.ts's (a) scenario
// (KAR-951): the ALT/NEU pair Kais actually uploaded (server-only directory,
// never committed — INPUT_DIR below, addressed by absolute path only).
// Assertions are aggregate/structural/counter-only (sheet names, row counts,
// presence of specific status codes) — never a literal cell value, code, or
// filename from that corpus as a test literal (Master-Prompt confidentiality
// discipline, same as every other real-files test in this directory).
//
// tdd-guard:skip — real-file regression/observation test, not a unit-level
// behavior spec (behavior is unit-tested in export.test.ts via synthetic
// fixtures).

import { describe, it, expect } from 'vitest'
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import ExcelJS from 'exceljs'
import { loadExcelWorkbook } from '../../workbook-adapter'
import { detectMultiQaf, multiQafDetectionInputFromExcelJs } from '../../qaf-type-detector'
import { assembleMultiQafContainer } from '../container-assembly'
import { runMultiQafCompareFlow } from '../compare-flow'
import { buildMultiQafExportWorkbook } from '../export'
import type { MultiQafContainer } from '../types'

const INPUT_DIR = '/root/aria/work/qaf-compare-kar824/input'
const KAR951_PAIR_DIR = path.join(INPUT_DIR, 'kais-test-2026-07-13')
const KAR951_ALT_PATH = path.join(KAR951_PAIR_DIR, 'ALT_original.xlsx')
const KAR951_NEU_PATH = path.join(KAR951_PAIR_DIR, 'NEU_modified.xlsx')

async function assembleFromBuffer(buffer: Buffer): Promise<MultiQafContainer> {
  const wb = await loadExcelWorkbook(buffer)
  const detection = detectMultiQaf(multiQafDetectionInputFromExcelJs(wb))
  return assembleMultiQafContainer({ worksheets: wb.worksheets }, detection, { fileName: null, fileHash: null })
}

const REQUIRED_SHEETS = ['Uebersicht', 'Varianten_Matching', 'Summary_Kennzahlen', 'Material_Diff', 'Fertigungsprofile', 'Rekonziliation', 'Aggregat_Impact']

describe.skipIf(!existsSync(KAR951_ALT_PATH) || !existsSync(KAR951_NEU_PATH))('KAR-949 — Multi-QAF export real-file regression (env-gated)', () => {
  it(
    "Kais' Multi-QAF pair exports to a parsable workbook with all 7 sheets; Summary_Kennzahlen has changed AND nicht_ermittelbar rows; Aggregat_Impact has gate rows",
    async () => {
      const alt = await assembleFromBuffer(readFileSync(KAR951_ALT_PATH))
      const neu = await assembleFromBuffer(readFileSync(KAR951_NEU_PATH))
      const result = runMultiQafCompareFlow(alt, neu)

      const buffer = await buildMultiQafExportWorkbook({
        generatedAtLabel: '2026-07-14 00:00',
        altFileName: 'ALT_original.xlsx',
        neuFileName: 'NEU_modified.xlsx',
        altContainer: alt,
        neuContainer: neu,
        result,
        persistedOverrides: [],
      })

      // ExcelJS read-back — proves the buffer is a genuinely valid, parsable
      // .xlsx, not just "some bytes were written".
      const wb = new ExcelJS.Workbook()
      await wb.xlsx.load(buffer as unknown as ArrayBuffer)
      const sheetNames = wb.worksheets.map((w) => w.name)
      for (const s of REQUIRED_SHEETS) expect(sheetNames).toContain(s)
      expect(sheetNames).toHaveLength(REQUIRED_SHEETS.length)

      const kennzahlenWs = wb.getWorksheet('Summary_Kennzahlen')!
      let changedCount = 0
      let nichtErmittelbarCount = 0
      kennzahlenWs.eachRow((row) => {
        const vals = (row.values as unknown[]).map((v) => String(v ?? ''))
        if (vals.includes('changed')) changedCount += 1
        if (vals.includes('nicht_ermittelbar')) nichtErmittelbarCount += 1
      })
      console.log(`[KAR-949 multi-qaf export real-file] changedRows=${changedCount} nichtErmittelbarRows=${nichtErmittelbarCount}`)
      expect(changedCount).toBeGreaterThan(0)
      expect(nichtErmittelbarCount).toBeGreaterThan(0)

      const aggWs = wb.getWorksheet('Aggregat_Impact')!
      let gateRowCount = 0
      const gateIds = ['compatible_currencies', 'volumes_available', 'no_duplicates_or_ambiguous', 'consistent_units', 'valid_baseline', 'no_blocked_critical_mappings']
      aggWs.eachRow((row) => {
        const vals = (row.values as unknown[]).map((v) => String(v ?? ''))
        if (gateIds.some((g) => vals.some((v) => v.includes(`[${g}]`)))) gateRowCount += 1
      })
      console.log(`[KAR-949 multi-qaf export real-file] gateRows=${gateRowCount} reviewRequired=${result.reviewRequired}`)
      expect(gateRowCount).toBeGreaterThan(0)
    },
    120_000,
  )
})
