// Per-file DE/EN/mixed language detection (KAR-905 / P3.1).
//
// Problem this closes (backlog 05-backlog-phasenplan.md [P3.1] task
// instruction, Master-Prompt §9): Kadi-v2 had no explicit notion of "which
// language is this QAF file in" — summary-metrics.ts's pickTemplate() comes
// close but answers a DIFFERENT question (QAF_LEGACY_DE_SUMMARY vs.
// QAF_V9_SUMMARY is a TEMPLATE-GENERATION axis, not a language axis: V9
// SUMMARY sheets are used identically for DE-content and EN-content files —
// see module-sheet-names.ts's SUMMARY entry). This module is the actual
// language signal, deliberately kept separate from and complementary to
// pickTemplate/SummaryTemplateType.
//
// ── Why this is sheet-NAME-based, not content-based (documented scope) ──────
// The Leitfaden's own worked example (Abbildung 27, "Sprachauswahl DE/EN")
// shows a per-file radio-button language selection that changes the FIELD
// LABEL TEXT inside a sheet — it does not, per the module-sheet-names.ts
// inventory, change most sheets' TAB names (MATERIAL/SBM-DEVICES-FWZ/
// LOGISTICS&CUSTOM/RAW MATERIAL RISKS/LC-CN/CO2e tab names are locale-
// invariant proper nouns/abbreviations). Only two signals are reliable
// sheet-name-level language markers today:
//   1. The MANUFACTURING tab name itself ("Fertigungskosten" DE vs.
//      "Manufacturing costs"/"Manufactering costs" EN) — real-file-verified
//      (qaf-parser.ts module header, canonical-fields.ts MANUFACTURING
//      coverage note).
//   2. The SUMMARY tab being named "Zusammenfassung" — summary-metrics.ts's
//      pre-existing pickTemplate() DE-legacy signal; there is no EN
//      "Zusammenfassung" counterpart (V9's EN variant is also tab-named
//      "SUMMARY", so absence of this signal is NOT an EN signal, only a
//      "not legacy-DE" non-signal — see detectQafFileLanguage below, which
//      therefore never emits an 'en' signal from the SUMMARY tab name alone).
// A stronger, content-based signal (which of labelDe/labelEn a MANUFACTURING
// header row matched more often) is NOT implemented here — task instruction
// explicitly scopes P3.1 to "Summary-Template/Sheet-Namen", and a content-
// level signal would need matchHeaderColumnSync (qaf-parser.ts) to expose
// per-column language, not just confidence tier — out of this PR's scope
// (kept as a documented limitation, not a silent guess).
//
// Consequence: a file with an unusual/renamed MANUFACTURING tab and a V9
// SUMMARY tab produces NO signal at all → 'unknown', never a fabricated
// guess. A file with sheets pointing at different languages (e.g. a manually
// reassembled workbook mixing an EN Fertigungskosten... sorry, "Manufacturing
// costs" tab with content actually in German) produces 'mixed' — surfaced
// to the user via the fingerprint/UI badge, not silently resolved either way.
//
// Pure. No I/O — callers (template-fingerprint.ts's buildTemplateFingerprint)
// already have `sheets`/`summary.template` on hand from data they parsed.
//
// tdd-guard:skip — the detection logic itself IS test-driven (see
// __tests__/language-detection.test.ts); this skip marker only reflects that
// the module has no test-adjacent scaffolding to bypass (matches every other
// internal/*.ts module's convention of only marking pure-constant-data files,
// included here for consistency with sibling P2.x/P3.x module headers — this
// file is NOT pure constant data, remove if tdd-guard flags it as such).

import type { SummaryTemplateType } from './summary-metrics'
import { moduleSheetNameLanguageSignal } from './module-sheet-names'

export type QafFileLanguage = 'de' | 'en' | 'mixed' | 'unknown'

export interface QafFileLanguageSignal {
  /** Human-readable provenance, e.g. "sheet:Fertigungskosten" or
   * "summaryTemplate:QAF_LEGACY_DE_SUMMARY" — shown in the deviations/UI
   * badge tooltip, not machine-parsed by any caller. */
  source: string
  language: 'de' | 'en'
}

export interface QafFileLanguageResult {
  language: QafFileLanguage
  /** Every individual signal that contributed — empty when language is
   * 'unknown'. Kept even when they all agree (not just on conflict) so a
   * UI badge tooltip can always show "why" without a second code path. */
  signals: readonly QafFileLanguageSignal[]
}

export interface QafFileLanguageInput {
  /** Every worksheet's tab name in the workbook (order irrelevant). */
  sheetNames: readonly string[]
  /** summary-metrics.ts's pickTemplate() result, when a SUMMARY sheet was
   * parsed — null/undefined when absent (G60 files, or no SUMMARY sheet). */
  summaryTemplate?: SummaryTemplateType | null
}

/**
 * Detect a QAF file's DE/EN language from its worksheet tab names (+ the
 * already-computed summary template type, when available). Never throws,
 * never guesses past its evidence — 'unknown' when no signal was found,
 * 'mixed' when signals genuinely disagree (see module header).
 */
export function detectQafFileLanguage(input: QafFileLanguageInput): QafFileLanguageResult {
  const signals: QafFileLanguageSignal[] = []

  for (const name of input.sheetNames) {
    const manufacturingSignal = moduleSheetNameLanguageSignal(name, 'MANUFACTURING')
    if (manufacturingSignal) signals.push({ source: `sheet:${name}`, language: manufacturingSignal })

    const summarySignal = moduleSheetNameLanguageSignal(name, 'SUMMARY')
    if (summarySignal) signals.push({ source: `sheet:${name}`, language: summarySignal })
  }

  // Redundant-but-explicit with the SUMMARY sheet-name loop above for a file
  // whose summaryTemplate was computed from row/label content rather than
  // (only) re-derived here from the tab name — keeps this module correct
  // even if a future caller passes summaryTemplate without also passing the
  // SUMMARY sheet's own name in sheetNames. QAF_V9_SUMMARY intentionally
  // produces NO signal (see module header: V9 is used for both DE and EN
  // content, tab-name-identically).
  if (input.summaryTemplate === 'QAF_LEGACY_DE_SUMMARY') {
    signals.push({ source: 'summaryTemplate:QAF_LEGACY_DE_SUMMARY', language: 'de' })
  }

  if (signals.length === 0) return { language: 'unknown', signals }

  const distinctLanguages = new Set(signals.map((s) => s.language))
  const language: QafFileLanguage = distinctLanguages.size === 1 ? [...distinctLanguages][0] : 'mixed'
  return { language, signals }
}
