/**
 * qaf-differences module — public entrypoint (ADR 019).
 *
 * Owner: SupplierPulse / QAF
 *
 * The auditable QAF Diff Engine (KAR-799). UI-independent: usable from server
 * actions, batch jobs, CLI and tests. Anything not re-exported here is internal
 * and may change without notice — no deep imports into internal/.
 *
 * tdd-guard:skip — pure re-export barrel; logic is tested in internal/__tests__.
 */

// ── Domain types ──────────────────────────────────────────────────────────────
export type {
  SourceRef,
  MoneyValue,
  QafSheet,
  FieldDiff,
  DiffStatus,
  StepMatch,
  MatchStatus,
  MatchMethod,
  MatchConfig,
  QafSummary,
  QafSummaryKey,
  SummaryField,
  FieldState,
  // PR #328 review fix (finding [2]/[3]): needed by page.tsx to type the
  // persisted g60_meta.rateDegradation read-back.
  FacetDegradation,
} from './internal/types'
export {
  PERCENT_FIELDS,
  isPercentField,
  DEFAULT_MATCH_CONFIG,
  ENGINE_VERSION,
} from './internal/types'

// ── Normalizer ────────────────────────────────────────────────────────────────
export {
  parseLocaleNumber,
  normalizeProcessName,
  normalizePosition,
  normalizeCurrency,
  isBlank,
  isNotApplicableValue,
  NOT_APPLICABLE_MARKERS,
} from './internal/normalizer'

// ── Diff ──────────────────────────────────────────────────────────────────────
export {
  computeFieldDiff,
  computeFieldDiffWithNotApplicable,
  computeNumericDelta,
  diffSteps,
  DEFAULT_DIFFER_BANDS_CONFIG,
} from './internal/differ'
export type { NumericDelta, DifferBandsConfig } from './internal/differ'

// ── Summary view-model (KPI tiles + form lines from qaf_summary_diff rows) ────
export {
  buildSummaryKpis,
  buildFormLines,
  buildBuckets,
  buildBridge,
  buildMetricsTable,
  buildNegotiation,
  buildOneTimeRows,
  sumOneTimeDeltas,
  pickCurrency,
  BUCKET_LABEL_DE,
  BRIDGE_MIN_STEP,
} from './internal/summary-view'
export type {
  SummaryDiffRowData,
  SummaryKpis,
  KpiValue,
  FormLine,
  BucketDatum,
  BucketKey,
  BridgeData,
  BridgeStep,
  BridgeCompositionPart,
  MetricsTableRow,
  Negotiation,
  NegotiationRow,
  OneTimeRow,
} from './internal/summary-view'

// ── G60 detail-QAF engine (V11 b3_core port, KAR-840 G60 stage 1) ─────────────
export {
  detectG60,
  detailTabs as g60DetailTabs,
  inputRates as g60InputRates,
  inputCard as g60InputCard,
  volumes as g60Volumes,
  extractTab as g60ExtractTab,
  extractFullTab as g60ExtractFullTab,
  parseG60Workbook,
  primaryStep as g60PrimaryStep,
  sheetFromCells as g60SheetFromCells,
  workbookFromSheets as g60WorkbookFromSheets,
  G60_RATES_SOURCE_CELLS,
  // KAR-966 item 1: speaking Preis-Kalkulator dropdown label per Kostenreiter tab.
  g60TabLabel,
  // PR #330 review fix (KAR-966 item 1): shared AO>0-gated/AT-tie-broken
  // primary-row selector — single source of truth for calculatorParamsFrom
  // (actions.ts) and g60TabLabel, which had drifted from each other.
  primaryComponentRow as g60PrimaryComponentRow,
} from './internal/g60/parser'
export type {
  CellGetter,
  G60Workbook,
  G60Rates,
  G60RatesSourceCells,
  G60InputCard,
  G60CardEntry,
  G60Volumes,
  G60Step,
  G60StepSourceCells,
  G60TabAggregate,
  G60ColumnOverrides,
  G60ComponentRow,
  G60ParseResult,
  G60MetricKey,
  G60DetectionConfig,
} from './internal/g60/parser'
// KAR-961/P4 — detectG60's config is now a first-class export (was inline
// literals before) so a future calibration pass can pass a widened config
// without reaching into internal/. DEFAULT_G60_DETECTION_CONFIG is the
// identity default detectG60() already uses when no config is passed.
export { DEFAULT_G60_DETECTION_CONFIG } from './internal/g60/parser'
export { analyzeG60Pair, G60_BUCKETS } from './internal/g60/analyze'
export { rehydrateG60File } from './internal/g60/rehydrate'
export { suggestStationForRow } from './internal/g60/stopwatch-map'
export { computeUnitPrice, EMPTY_UNIT_PRICE_PARAMS } from './internal/g60/calculator'
export type { UnitPriceParams, UnitPriceResult } from './internal/g60/calculator'
export type { StationMeasurement } from './internal/g60/stopwatch-map'
export {
  effParams as g60EffParams,
  recomputeTab as g60RecomputeTab,
  buildScenarioModel,
  recomputeScenario,
  scenarioBaseline,
  tabDetail as g60TabDetail,
} from './internal/g60/scenario'
export type {
  G60ScenarioGlobal,
  G60RowOverride,
  G60TabOverrides,
  G60ScenarioOverrides,
  G60ScenarioModel,
  G60ScenarioResult,
  G60ScenarioTabResult,
  G60TabDetail as G60TabDetailResult,
  G60DetailRow,
  G60TabTotals,
} from './internal/g60/scenario'
export type { G60TabDbRow, G60CardDbRow } from './internal/g60/rehydrate'
export {
  buildG60Buckets,
  buildG60Bridge,
  buildG60MoversInput,
  buildG60Anomalies,
  buildG60Levers,
  buildProdIndex,
  G60_CATEGORY_LABEL,
} from './internal/g60/view'
export type { G60AnomalyRow, G60Lever, G60ProdIndexRow } from './internal/g60/view'
export { g60WorkbookFromBuffer, g60WorkbookFromExcelJs } from './internal/g60/bridge'
export { buildG60Rows } from './internal/g60/persistence'
export type {
  G60PersistenceContext,
  G60Rowset,
  G60TabRow,
  G60InputCardRow,
  G60FileMeta,
} from './internal/g60/persistence'
// KAR-888/P0.3: G60 structure guard against silent wrong/empty numbers.
// KAR-894/P1.3 adds label-based column localization (locateG60ColumnAnchors)
// on top — same module, same export block.
export {
  validateG60TabHeader,
  validateG60InputRates,
  validateG60Structure,
  parseG60WorkbookGuarded,
  buildG60StructureIssues,
  locateG60ColumnAnchors,
  g60TabColumnRelocationToPlausibilityIssue,
  G60_STRUCTURE_GUARD_CONFIG,
  G60_HEADER_ROW,
  DEFAULT_RELOCATED_CONFIDENCE,
} from './internal/g60/structure-guard'
export type {
  G60StructureMismatch,
  G60StructureFinding,
  G60StructureReport,
  G60GuardedParseResult,
  G60StructureIssueInput,
  G60StructureGuardConfig,
  G60AnchorStatus,
  G60ColumnLocation,
  G60ColumnRelocation,
} from './internal/g60/structure-guard'
export type {
  G60Analysis,
  G60SideAggregate,
  G60MetricRow,
  G60ProdRow,
  G60DriverDiff,
  G60Bucket,
} from './internal/g60/analyze'
// KAR-913/P4.3: G60 Excel export (Delta-Übersicht, Produktion,
// Kalkulator-Treiber, Struktur-Plausibilität).
export { buildG60ExportWorkbook } from './internal/g60/export'
export type { G60ExportInput } from './internal/g60/export'

// ── Negotiation levers (V11 section 7, KAR-840) ───────────────────────────────
export { buildLevers, hasLeverKpiSignal, LEVER_KPI_DEFS } from './internal/levers'
export type { Lever, LeverDiffInput, LeverKpiDef } from './internal/levers'
export { buildLeversRun } from './internal/levers-run'
export type { LeversRun, LeverSpec } from './internal/levers-run'

// ── Projection / annual extrapolation (V11 section 5, KAR-840) ────────────────
export { computeProjection, defaultProjectionYears } from './internal/projection'
export type { Projection, ProjectionYear, ProjectionYearInput, ProjectionTotals } from './internal/projection'

// ── Comparison-scoped user inputs / debounced autosave (KAR-985) ──────────────
export {
  mergeQafComparisonUserInputs,
  normalizeQafComparisonUserInputsPatch,
  readQafProjectionUserInputs,
  readQafCalculatorUserInputs,
  validateQafComparisonUserInputsPatch,
} from './internal/comparison-user-inputs'
export type {
  QafComparisonUserInputs,
  QafComparisonUserInputsPatch,
  QafProjectionUserInputs,
  QafCalculatorUserInputs,
} from './internal/comparison-user-inputs'

// ── Price movers / tornado (V11 section 4, KAR-840) ───────────────────────────
export { buildMovers, topMovers, selectMovers } from './internal/movers'
export type { Movers, MoverRow, MoversInput, TopN, MoversReconciliation, MoversSelection } from './internal/movers'

// ── Summary metrics (Zusammenfassung money values + diff, KAR-840) ────────────
export { SUMMARY_METRIC_KEYS, parseSummaryMetrics, diffSummaryMetrics, METRIC_LABELS_DE } from './internal/summary-metrics'
export type {
  SummaryMetricKey,
  SummaryMetricValue,
  SummaryMetricsParse,
  SummaryMetricDiff,
  SummaryTemplateType,
  MetricLocateMethod,
} from './internal/summary-metrics'

// ── Matching cascade (Pflichtkern, spec B3) ───────────────────────────────────
export { matchSteps, matchStepsWithPins } from './internal/matcher'
export { deriveProductLineTags } from './internal/product-line-tags'
export type { ManualPin } from './internal/matcher'

// ── Manual field-mapping overrides (KAR-912/P4.2) ─────────────────────────────
export {
  applyFieldMappingOverrides,
  normalizeOverrideRowKey,
  upsertFieldMappingOverride,
  removeFieldMappingOverride,
  carryForwardFieldMappingOverrides,
  fieldMappingOverrideDroppedIssues,
  isOverridableFieldKey,
} from './internal/field-mapping-override'
export type { FieldMappingOverride, RowIdentity, CarryForwardResult } from './internal/field-mapping-override'

// ── Summary sheet parser (Zusammenfassung/Summary, spec A3) ────────────────────
export { parseSummary, gridFromCells } from './internal/summary-parser'
export {
  DECLARED_COMPARISON_TYPES,
  normalizeDeclaredComparisonType,
  isDeclaredComparisonType,
  COMPARISON_TYPE_EVIDENCE_ISSUE_TYPES,
  type DeclaredComparisonType,
} from './internal/declared-comparison-type'
export {
  partitionDifferenceRecords,
  PARTITION_DELTA_TOLERANCE,
  type PartitionedRecords,
} from './internal/record-partition'
export { rowsFromMetricDiffs, type MetricDiffLike } from './internal/summary-view'
export {
  deriveComparability,
  type ComparabilityStatus,
  type DerivedComparability,
} from './internal/comparability'
export { isEngineConfigVersionAtLeast } from './internal/engine-config'
export {
  coverageFromPersistedMatrix,
  CAPABILITY_MODULE_LABELS_DE,
  CAPABILITY_STATUS_LABELS_DE,
  type CoverageEntry,
} from './internal/capability/coverage-view'
export {
  buildCanonicalExport,
  withCanonicalContentHash,
  decimalString,
  deriveAnalysisStatus,
  CANONICAL_SCHEMA_VERSION,
  CANONICAL_EXPORT_PROFILE,
  type CanonicalExportInput,
  type CanonicalDocumentInput,
} from './internal/canonical-export'
export { buildOverviewRun, type OverviewRun } from './internal/overview-run'
export { buildCatalog } from './internal/all-differences'
export { differencesFromManufacturing } from './internal/differences-from-manufacturing'
export { differencesFromMaterial } from './internal/differences-from-material'

// ── Workbook adapter (ExcelJS → engine, server-only, spec B-Parser) ───────────
export {
  worksheetToGrid,
  parseSummaryFromWorkbook,
  parseSummarySheet,
  parseSummarySheetFromWorkbook,
  parseQafFile,
  loadExcelWorkbook,
  summarizeWorkbookSheets,
  semanticActiveRange,
  SEMANTIC_ACTIVE_RANGE_MAX_ROWS,
  SEMANTIC_ACTIVE_RANGE_MAX_COLS,
  // KAR-961/P4 — single-cell ExcelJS→plain-value resolver (formula/merge/
  // richtext aware), needed by actions.ts's cost-allocation-family
  // integration to build a CellGetter for extractCostAllocationMeta without
  // a second, family-specific ExcelJS bridge (g60/bridge.ts already reuses
  // this exact function internally for the same reason).
  resolveCell,
} from './internal/workbook-adapter'
export type { WorkbookSheetSummary, SemanticActiveRange } from './internal/workbook-adapter'

// ── Untrusted-Excel hardening (KAR-914/P4.4, Master-Prompt §20) ───────────────
export {
  inspectZipStructure,
  ZipStructureError,
  computeRealUncompressedSize,
  evaluateZipBombRisk,
  DEFAULT_ZIP_BOMB_LIMITS,
  evaluateSheetDimensions,
  DEFAULT_SHEET_DIMENSION_LIMITS,
  detectMacroPresence,
  detectExternalWorkbookLinks,
  runPreParseWorkbookSafetyCheck,
  runPreParseLegacyBiffCheck,
  DEFAULT_BIFF_LIMITS,
  workbookSafetyToPlausibilityIssues,
} from './internal/workbook-safety'
export { isLegacyBiffBuffer, loadLegacyWorkbook } from './internal/legacy-workbook-shim'
export type {
  ZipEntryInfo,
  ZipStructureInspection,
  WorkbookSafetyVerdict,
  RealSizeCheckResult,
  ZipBombLimits,
  SheetDimensionLimits,
  WorkbookSafetyResult,
  WorkbookPreParseCheck,
} from './internal/workbook-safety'

// ── WAF/LAF/LEK format detection — Detect & Reject (KAR-920/P5.3) ────────────
export { detectForeignForm, foreignFormWorkbookFromExcelJs, HEADER_SCAN_ROWS } from './internal/foreign-form-detection'
export type { ForeignFormKind, ForeignFormWorkbook, ForeignFormDetection } from './internal/foreign-form-detection'

// ── Multi-QAF type detection + safe degradation (KAR-926/Multi-QAF-Programm P0.1) ─
export {
  detectMultiQaf,
  multiQafRejectionMessage,
  multiQafDetectionToPlausibilityIssue,
  multiQafDetectionInputFromExcelJs,
  DEFAULT_MULTI_QAF_DETECTION_CONFIG,
  HEADER_SCAN_ROWS as MULTI_QAF_HEADER_SCAN_ROWS,
  VARIANT_BAND_COL_FROM,
  VARIANT_BAND_COL_TO,
  MATERIAL_FORMULA_SCAN_ROWS,
  multiQafDetectionMetaFragment,
} from './internal/qaf-type-detector'
export type {
  MultiQafDetectionConfig,
  MultiQafDetectionInput,
  MultiQafSignalId,
  MultiQafSignalStrength,
  MultiQafSignalFinding,
  MultiQafClassification,
  MultiQafDetectionResult,
} from './internal/qaf-type-detector'

// ── Multi-QAF container domain model (KAR-929/Multi-QAF-Programm P1.1) ──────
// Pure types + pure core functions (identity, serialization, canonical-
// engine bridge). No parser wired to a real workbook yet (P1.2+), no DB
// migration, no ingest wiring — see internal/multi-qaf/types.ts module
// header for the full scope statement.
export { MULTI_QAF_MODEL_VERSION, columnLetterToIndex, columnIndexToLetter, KNOWN_VARIANT_DIMENSION_KEYS } from './internal/multi-qaf/types'
export type {
  MultiQafCellRef,
  MultiQafFormulaValue,
  MultiQafMoneyAmount,
  KnownVariantDimensionKey,
  VariantDimensionValue,
  VariantDimensions,
  VariantDimensionDescriptor,
  VariantActiveState,
  VariantDefinition,
  VariantMatrixRowValidationStatus,
  VariantMatrixRow,
  SharedCostProfileKind,
  SharedCostProfile,
  ProfileBindingEvidenceKind,
  VariantProfileBinding,
  ColumnClassificationKind,
  ColumnClassificationEvidence,
  ColumnClassification,
  VirtualVariantMaterialRow,
  VirtualVariantSummaryTotals,
  VirtualQafVariant,
  MultiQafWarningSeverity,
  MultiQafWarning,
  MultiQafSummaryAggregation,
  MultiQafTemplateFamily,
  MultiQafTemplateFingerprint,
  MultiQafSourceWorkbookMeta,
  MultiQafMetadataValue,
  MultiQafLanguage,
  MultiQafContainer,
} from './internal/multi-qaf/types'
export {
  normalizeDimensionValue,
  makeDimensionValue,
  buildCompositeCanonicalKey,
  hasVariantIdentity,
  deriveActiveState,
} from './internal/multi-qaf/identity'
export {
  serializeMultiQafContainer,
  deserializeMultiQafContainer,
  serializeVirtualQafVariants,
  deserializeVirtualQafVariants,
} from './internal/multi-qaf/serialization'
export { virtualVariantSummary, virtualVariantSummaryMetrics, toCanonicalInputs } from './internal/multi-qaf/bridge'

// ── Formula-Lineage Summary↔Detail (KAR-933/Multi-QAF-Programm P1.5) ────────
export {
  parseFormulaReferences,
  classifyFormulaShape,
  buildColumnLineage,
  detailColumnsFeedingSummaryColumn,
  summaryColumnsFedByDetailColumn,
  isOrphanedDetailColumn,
  formulaLineageNotesFromGraph,
  MAX_FORMULA_CELLS_PER_SHEET,
  MAX_LINEAGE_DEPTH,
} from './internal/multi-qaf/formula-lineage'
export type {
  ParsedCellReference,
  FormulaShapeKind,
  FormulaShapeClassification,
  FormulaLineageWarning,
  ColumnLineageEdge,
  DetailSheetCandidateColumns,
  ColumnLineageGraph,
  BuildColumnLineageOptions,
  DetailColumnHit,
  DetailColumnLineageStatus,
  DetailColumnLineageUnknownReason,
  DetailColumnLineageResult,
} from './internal/multi-qaf/formula-lineage'

// ── Multi-QAF variant header-block parser + column classifier
// (KAR-930/Multi-QAF-Programm P1.2) ──────────────────────────────────────
// Pure grid-parsing functions producing VariantDefinition[]/
// ColumnClassification[] from a Summary/BOM-sheet grid — see
// internal/multi-qaf/header-parser.ts module header for the full algorithm.
// Conservative by design (task instruction): a caller only invokes this
// once qaf-type-detector.ts's detectMultiQaf has already confirmed the
// workbook — not enforced by this module itself, and NOT wired into any
// ingest/upload path in this PR (P2's job).
export {
  parseVariantHeaderBlock,
  headerParserInputFromWorksheet,
  locateSlotIndexRow,
  locateVolumeRows,
  DEFAULT_COL_FROM,
  DEFAULT_COL_TO,
  DEFAULT_ROW_FROM,
  DEFAULT_ROW_TO,
} from './internal/multi-qaf/header-parser'
export type {
  HeaderParserGridInput,
  HeaderParserOptions,
  HeaderParserResult,
  SlotIndexRowResult,
  VolumeRowMatch,
} from './internal/multi-qaf/header-parser'
export {
  classifyColumn,
  parseDifferenceFormula,
  parsePercentFormula,
  parseSumRangeFormula,
  isCommentLabel,
} from './internal/multi-qaf/column-classifier'
export type { ColumnClassificationFacts, ColumnClassificationContext } from './internal/multi-qaf/column-classifier'

// ── Fertigungs-/Rüst-Profile-Parser + Bindungs-Auflösung
// (KAR-932/Multi-QAF-Programm P1.4) ──────────────────────────────────────
// Pure profile-block detection (grid-level) + variant→profile binding
// resolution + ExcelJS-workbook-level candidate-sheet selection (incl.
// Orphan-Hidden-Sheet-Ausschluss) — see internal/multi-qaf/profile-parser.ts
// module header for the full algorithm + real-file evidence. No ingest
// wiring, no container assembly (P2.1's job).
export {
  parseSharedCostProfileBlocks,
  locateVolumeBandLookupTable,
  locateManufacturingSummaryRow,
  resolveVariantProfileBindings,
  reconcileProfileToSummary,
  profileParserInputFromWorksheet,
  sharedCostProfileCandidateSheets,
  sharedCostProfilesFromWorkbook,
  DEFAULT_PROFILE_COL_FROM,
  DEFAULT_PROFILE_COL_TO,
  DEFAULT_PROFILE_ROW_FROM,
  DEFAULT_PROFILE_ROW_TO,
  DEFAULT_LABEL_SCAN_WINDOW,
  MIN_VOLUME_BAND_LOOKUP_ROWS,
  MAX_VOLUME_BAND_LOOKUP_ROWS,
  LITERAL_BINDING_ABS_TOLERANCE,
  LITERAL_BINDING_REL_TOLERANCE,
} from './internal/multi-qaf/profile-parser'
export type {
  ProfileParserGridInput,
  ProfileBlockScanOptions,
  VariantColumnRef,
  ResolveVariantProfileBindingsResult,
  ProfileSummaryReconciliationResult,
  ManufacturingProfileFindingKind,
  SharedCostProfileCandidateSheets,
  SharedCostProfilesFromWorkbookResult,
} from './internal/multi-qaf/profile-parser'

// ── Candidate-sheet plausibility (KAR-927 adversarial-review fix, P0.2) ──────
export { normalizeIgnoredCandidateSheets } from './internal/candidate-sheet-plausibility'
export type {
  IgnoredCandidateSheetEntry,
  LegacyOrIgnoredCandidateSheetEntry,
  IgnoredCandidateSheetsMeta,
} from './internal/candidate-sheet-plausibility'

// ── MATERIAL sheet parser (KAR-897/P1.6) ──────────────────────────────────────
export {
  isMaterialSheetName,
  findMaterialWorksheet,
  findMaterialHeaderRow,
  matchMaterialHeaderColumn,
  parseMaterialWorksheet,
  parseMaterialSheet,
  materialRowsForReconciliation,
  materialRowsFromPersistedMeta,
  materialParseMetaToPlausibilityIssue,
  groupMaterialRowsByPosition,
  materialRowLogicalKey,
  CORE_MATERIAL_FIELD_KEYS,
  MATERIAL_UNIT_RAW_MATERIAL_RISK,
  MATERIAL_UNIT_PURCHASED_PART,
} from './internal/material-parser'
export type {
  MaterialRowValues,
  MaterialFieldKey,
  MaterialRow,
  MaterialParseMeta,
  MaterialParseResult,
  MaterialPositionGroup,
  PersistedMaterialMeta,
} from './internal/material-parser'

// ── SBM-DEVICES-FWZ sheet parser (KAR-898/P1.7) ───────────────────────────────
export {
  isSbmSheetName,
  findSbmWorksheet,
  findSbmHeaderRow,
  matchSbmHeaderColumn,
  parseSbmWorksheet,
  parseSbmSheet,
  sbmRowsForReconciliation,
  sbmRowsFromPersistedMeta,
  sbmParseMetaToPlausibilityIssue,
  classifySbmToolDeviceType,
  CORE_SBM_FIELD_KEYS,
  SBM_VERRECHNUNGSFORM_VALUES,
  SBM_DEVICE_CATEGORY_TABLE,
} from './internal/sbm-parser'
export type {
  SbmRowValues,
  SbmFieldKey,
  SbmRow,
  SbmParseMeta,
  SbmParseResult,
  SbmVerrechnungsform,
  SbmDeviceClassificationTag,
  SbmDeviceCategoryEntry,
  SbmDeviceClassificationResult,
  PersistedSbmMeta,
} from './internal/sbm-parser'

// ── RAW MATERIAL RISKS sheet parser + Rohstoffzuschlag-Validierung (KAR-902/P2.3) ─
export {
  isRmrSheetName,
  findRmrWorksheet,
  findRmrHeaderRow,
  matchRmrHeaderColumn,
  parseRmrWorksheet,
  parseRmrSheet,
  rmrRowsForReconciliation,
  rmrRowsFromPersistedMeta,
  rmrParseMetaToPlausibilityIssue,
  validateRmrRawMaterialSurcharge,
  evaluateRmrValidation,
  rmrValidationResultToPlausibilityIssue,
  checkRmrValidation,
  CORE_RMR_FIELD_KEYS,
  RMR_VALIDATION_CONFIG,
} from './internal/rmr-parser'
export type {
  RmrRowValues,
  RmrFieldKey,
  RmrRow,
  RmrBlockType,
  RmrParseMeta,
  RmrParseResult,
  PersistedRmrMeta,
  RmrValidationCheckId,
  RmrValidationStatus,
  RmrValidationResult,
  RmrValidationConfig,
  RmrValidationInput,
} from './internal/rmr-parser'

// ── LOGISTICS&CUSTOM sheet parser + Reconciliation (KAR-903/P2.4) ───────────
export {
  isLogisticsSheetName,
  findLogisticsWorksheet,
  findLogisticsHeaderRow,
  matchLogisticsHeaderColumn,
  parseLogisticsWorksheet,
  parseLogisticsSheet,
  logisticsRowsForReconciliation,
  logisticsRowsFromPersistedMeta,
  validateLogisticsCostFormula,
  validateLogisticsIncotermDomain,
  evaluateLogisticsValidation,
  logisticsValidationResultToPlausibilityIssue,
  checkLogisticsValidation,
  CORE_LOGISTICS_FIELD_KEYS,
  LOGISTICS_INCOTERM_VALUES,
  LOGISTICS_VALIDATION_CONFIG,
} from './internal/logistics-parser'
export type {
  LogisticsRowValues,
  LogisticsFieldKey,
  LogisticsRow,
  LogisticsParseMeta,
  LogisticsParseResult,
  PersistedLogisticsMeta,
  LogisticsValidationCheckId,
  LogisticsValidationStatus,
  LogisticsValidationResult,
  LogisticsValidationConfig,
  LogisticsValidationInput,
} from './internal/logistics-parser'

// ── LOCAL CONTENT CHINA (LC-CN) sheet parser + duale LC-Rate (KAR-904/P2.5) ─
export {
  isLccnSheetName,
  findLccnWorksheet,
  matchLccnLabelCell,
  parseLccnWorksheet,
  parseLccnSheet,
  lccnForReconciliation,
  lccnFromPersistedMeta,
  validateLccnTotalProductionCost,
  validateLccnLcRateReadings,
  validateLccnLcRateComplement,
  evaluateLccnValidation,
  lccnValidationResultToPlausibilityIssue,
  checkLccnValidation,
  classifyLcProcess,
  checkLcProcessDeclarationAgainstClassification,
  LC_PROCESS_CLASSIFICATION_TABLE,
  CORE_LCCN_FIELD_KEYS,
  LCCN_VALIDATION_CONFIG,
} from './internal/lccn-parser'
export type {
  LccnSummaryValues,
  LccnFieldKey,
  LccnParseMeta,
  LccnParseResult,
  PersistedLccnMeta,
  LccnValidationCheckId,
  LccnValidationStatus,
  LccnValidationResult,
  LccnValidationConfig,
  LccnValidationInput,
  LcProcessClassificationTag,
  LcProcessClassificationEntry,
  LcProcessClassificationResult,
} from './internal/lccn-parser'

// ── CARBON FOOTPRINT (CO2e) sheet parser + Emissionen-Material (KAR-904/P2.5) ─
export {
  isCo2eSheetName,
  findCo2eWorksheet,
  matchCo2eSummaryLabelCell,
  matchCo2eMaterialHeaderColumn,
  parseCo2eSheet,
  co2eSummaryForReconciliation,
  co2eMaterialRowsForReconciliation,
  co2eFromPersistedMeta,
  validateCo2eMaterialEmissionsFormula,
  evaluateCo2eValidation,
  co2eValidationResultToPlausibilityIssue,
  checkCo2eValidation,
  CORE_CO2E_SUMMARY_FIELD_KEYS,
  CORE_CO2E_MATERIAL_FIELD_KEYS,
  CO2E_VALIDATION_CONFIG,
} from './internal/co2e-parser'
export type {
  Co2eSummaryValues,
  Co2eSummaryFieldKey,
  Co2eMaterialRowValues,
  Co2eMaterialFieldKey,
  Co2eFieldKey,
  Co2eSummaryParseMeta,
  Co2eSummaryParseResult,
  Co2eMaterialRow,
  Co2eMaterialParseMeta,
  Co2eMaterialParseResult,
  Co2eParseResult,
  PersistedCo2eMeta,
  Co2eValidationCheckId,
  Co2eValidationStatus,
  Co2eValidationResult,
  Co2eValidationConfig,
  Co2eValidationInput,
} from './internal/co2e-parser'

// ── Baseline selection (spec B5) ──────────────────────────────────────────────
export { selectBaseline } from './internal/baseline'
export type { QafFileRef, BaselineMode, BaselineStatus, BaselineSelection, BaselineOptions } from './internal/baseline'

// ── Plausibility (spec B12) ───────────────────────────────────────────────────
export { checkPlausibility, checkSummaryIdentityPlausibility } from './internal/plausibility'
export type { PlausibilityIssue, PlausibilitySeverity, PlausibilityInput } from './internal/plausibility'

// ── Bilingual message encode/decode (KAR-906/P3.2) ─────────────────────────
// decodeBilingual is consumed by UI components (qaf-comparison-detail.tsx,
// qaf-g60-detail.tsx) to render a persisted qaf_plausibility_issue.explanation
// value in the active UI locale — this is the one internal helper the UI
// layer needs, so it is re-exported here rather than deep-imported.
export { encodeBilingual, decodeBilingual } from './internal/bilingual-message'
export type { DecodedMessage } from './internal/bilingual-message'

// ── Fehlerreport-Regel-Engine R1-R6 (KAR-889/P0.4) ────────────────────────────
export {
  evaluateRuleEngine,
  classifyFieldState,
  canonicalizeFieldLabel,
  disambiguateLabels,
  blockedStepFields,
  ruleViolationToPlausibilityIssue,
  RULE_ENGINE_CONFIG,
} from './internal/rule-engine'
export type {
  RuleId,
  RuleEnforcement,
  RuleEngineConfig,
  RuleViolation,
  RuleEngineInput,
  RuleEngineFileInput,
  ComparisonSide,
} from './internal/rule-engine'

// ── Root-cause (spec B8) ──────────────────────────────────────────────────────
export { computeRootCause } from './internal/root-cause'
export type { RootCauseInput, RootCauseResult, RootCauseDriver, StepDiffSummary } from './internal/root-cause'

// ── Comparison orchestrator (spec A2/B) ───────────────────────────────────────
export { compareQafPair } from './internal/compare'
export type { QafFileParsed, StepComparison, QafComparisonResult } from './internal/compare'

// ── Batch orchestration (group by part number, compare, spec A2.1) ────────────
export { buildBatchComparisons } from './internal/batch'
export type { BatchGroupResult } from './internal/batch'

// ── Excel export (8 sheets, reference quality, spec B9) ───────────────────────
export { buildQafExportWorkbook } from './internal/export'
export type { QafExportInput } from './internal/export'

// ── Export rehydration (persisted qaf_* rows -> workbook, KAR-840 PR1) ─────────
export {
  partToSummary,
  rehydrateFile,
  rehydrateExportInput,
  buildExportWorkbookFromRows,
  summaryMetricsFromRows,
  resolvePersistedRuleEnforcement,
  resolvePersistedEngineConfig,
  resolveReplaceMultiQafDetectionConfig,
} from './internal/rehydrate'
export type { PartRow, FileRow, RehydratedFile, RehydrateExportArgs } from './internal/rehydrate'

// ── Persistence mapper (engine -> qaf_* rows, spec B10) ───────────────────────
export {
  buildComparisonRowset,
  buildManufacturingStepRow,
  buildSummaryMetricRows,
  recompareReplacedTables,
  RECOMPARE_REPLACED_CORE_TABLES,
} from './internal/persistence-mapper'
export type {
  PersistenceContext,
  ComparisonRowset,
  ComparisonRow,
  StructureChangeRow,
  PlausibilityIssueRow,
  RootCauseRow,
  SummaryDiffRow,
  SummaryMetricRow,
  ManufacturingStepRow,
} from './internal/persistence-mapper'

// ── Template fingerprint + known/modified/unknown classification (KAR-895/P1.4) ─
export {
  computeTemplateFingerprintStructure,
  hashTemplateFingerprintStructure,
  classifyTemplateFingerprint,
  buildTemplateFingerprint,
  templateFingerprintToPlausibilityIssue,
  summaryLocatedKeys,
  MANUFACTURING_EXPECTED_CANONICAL_IDS,
  MATERIAL_EXPECTED_CANONICAL_IDS,
  SBM_EXPECTED_CANONICAL_IDS,
  RMR_EXPECTED_CANONICAL_IDS,
  SUMMARY_EXPECTED_CANONICAL_IDS_BY_TEMPLATE,
  TEMPLATE_FINGERPRINT_CONFIG,
  TEMPLATE_FINGERPRINT_VERSION,
  QAF_V9_SUMMARY_PROFILE,
  QAF_LEGACY_DE_SUMMARY_PROFILE,
  G60_DETAIL_PROFILE,
  KNOWN_TEMPLATE_PROFILES,
} from './internal/template-fingerprint'
export type {
  TemplateFingerprintSheetSummary,
  TemplateFingerprintSummaryInput,
  TemplateFingerprintManufacturingInput,
  TemplateFingerprintMaterialInput,
  TemplateFingerprintSbmInput,
  TemplateFingerprintRmrInput,
  TemplateFingerprintG60Input,
  TemplateFingerprintInput,
  TemplateFingerprintSummaryFacet,
  TemplateFingerprintManufacturingFacet,
  TemplateFingerprintMaterialFacet,
  TemplateFingerprintSbmFacet,
  TemplateFingerprintRmrFacet,
  TemplateFingerprintG60Facet,
  TemplateFingerprintStructure,
  TemplateProfile,
  TemplateClassification,
  TemplateClassificationResult,
  TemplateFingerprintClassificationConfig,
  TemplateFingerprintResult,
} from './internal/template-fingerprint'

// ── Central versioned engine config (KAR-896/P1.5, Regel-Governance) ─────────
export { DEFAULT_ENGINE_CONFIG, validateEngineConfig, buildEngineConfigDelta } from './internal/engine-config'
export type { EngineConfig, EngineConfigSectionKey, EngineConfigDelta } from './internal/engine-config'

// ── Confidence-/Provenance-UI read-model (KAR-911/P4.1) ──────────────────────
export { extractDegradedModules, degradedModulesSentence } from './internal/module-degradation'
export type { DegradedModule, DegradationMetaInput } from './internal/module-degradation'

// ── Consolidated Zelle→Ergebnis Explain-Panel provenance (KAR-922/P6.2) ──────
export {
  buildManufacturingExplainAttributes,
  buildMaterialExplainAttributes,
  buildSbmExplainAttributes,
  buildRmrExplainAttributes,
  buildLogisticsExplainAttributes,
  buildSummaryExplainAttributes,
  buildQafGuideRequirement,
} from './internal/explain-provenance'
export type {
  ExplainStatus,
  ExplainValue,
  ExplainSideAttributes,
  ExplainAttributes,
  RuleFindingLike,
  RowModuleAdapterInput,
  SummarySideInput,
  SummaryExplainInput,
  MappingMethodKind,
  QafGuideRequirementValue,
} from './internal/explain-provenance'

// ── Multi-QAF material-matrix parser (KAR-931/P1.3) ──────────────────────────
export {
  parseMaterialMatrix,
  locateMaterialMatrixHeader,
  materialMatrixInputFromWorksheet,
  materialMatrixScanBoundsFromWorksheet,
  MATERIAL_MATRIX_MAX_ROWS,
  MATERIAL_MATRIX_MAX_COLS,
  MATERIAL_MATRIX_HEADER_SCAN_MAX_ROWS,
  MATERIAL_MATRIX_TOTAL_ROW_SCAN_WINDOW,
} from './internal/multi-qaf/material-matrix-parser'
export type {
  MaterialMatrixGridInput,
  MaterialMatrixOptions,
  MaterialMatrixParseResult,
  MaterialMatrixReconciliationStatus,
  MaterialMatrixReconciliationResult,
} from './internal/multi-qaf/material-matrix-parser'

// ── Multi-QAF template-fingerprint family extension (KAR-934/P1.6, last P1
// item) ────────────────────────────────────────────────────────────────────
// Classifies an already-detected (qaf-type-detector.ts)/already-parsed
// (header-parser.ts) Multi-QAF workbook against the 3 known Multi-QAF
// template families (m_qaf_1_0/m_qaf_2_0/qaf_8_1_custom_multi) — see
// internal/multi-qaf/template-fingerprint.ts module header for the full
// design rationale. Additive to ../template-fingerprint.ts's standard-QAF
// classification (untouched except for exporting its own stableStringify
// helper for reuse). No ingest wiring in this PR (P2's job, same discipline
// as header-parser.ts/profile-parser.ts above).
export {
  fingerprintMultiQafTemplate,
  fingerprintMultiQafTemplateFromExcelJs,
  multiQafTemplateFingerprintInputFromExcelJs,
  toMultiQafContainerFingerprint,
  KNOWN_MULTI_QAF_TEMPLATE_PROFILES,
  MQAF_V1_PROFILE,
  MQAF_V2_PROFILE,
  QAF_81_CUSTOM_MULTI_PROFILE,
} from './internal/multi-qaf/template-fingerprint'
export type {
  MultiQafTemplateFingerprintInput,
  MultiQafTemplateFingerprintResult,
  MultiQafTemplateSemanticSignature,
  MultiQafFamilyClassification,
  MultiQafFamilyProfile,
  MultiQafTemplateFingerprintFromExcelJsOptions,
} from './internal/multi-qaf/template-fingerprint'
export { locateVariantHeaderBlockOnSheet } from './internal/multi-qaf/template-fingerprint'

// ── Multi-QAF container assembly + VirtualQafVariant generation
// (KAR-935/Multi-QAF-Programm P2.1) ─────────────────────────────────────────
// Orchestrates the 6 merged P1 modules above into ONE MultiQafContainer
// (assembleMultiQafContainer) and generates the first VirtualQafVariant[]
// pass over it (generateVirtualVariants) — see internal/multi-qaf/
// container-assembly.ts module header for the full orchestration order and
// its honestly-scoped limits. resolveMultiQafContainerIngest is the
// fail-closed wrapper app/qaf-differences/actions.ts's ingest wiring calls.
export {
  assembleMultiQafContainer,
  generateVirtualVariants,
  resolveMultiQafContainerIngest,
  reviewStatusForMultiQafContainer,
} from './internal/multi-qaf/container-assembly'
export type {
  MultiQafContainerAssemblyOptions,
  MultiQafContainerIngestOutcome,
  MultiQafContainerReviewStatus,
} from './internal/multi-qaf/container-assembly'

// ── Multi-QAF Varianten-Matching mit Review-Workflow
// (KAR-936/Multi-QAF-Programm P2.2) ─────────────────────────────────────────
// The Master-Prompt §9 matching cascade (matchVariants) + persisted-override
// review workflow (matchVariantsWithOverrides) — see internal/multi-qaf/
// variant-matcher.ts module header for the full cascade design, result
// classes, and how container-assembly.ts's matchMaterialVariantsToContainer
// wires this in as its own cross-sheet fallback.
export {
  DEFAULT_VARIANT_MATCH_CONFIG,
  matchVariants,
  matchVariantsWithOverrides,
  identitySnapshotsEqual,
  identitySnapshotFor,
  findAllByIdentitySnapshot,
  replaceOverrideForVariant,
  removeActiveOverridesForVariant,
} from './internal/multi-qaf/variant-matcher'
export type {
  VariantMatchConfig,
  VariantMatchEvidence,
  VariantMatchStage,
  VariantMatchCandidateInfo,
  VariantMatchedResult,
  VariantAmbiguousResult,
  VariantSplitSuspectedResult,
  VariantMergeSuspectedResult,
  VariantUnmatchedLeftResult,
  VariantUnmatchedRightResult,
  VariantMatchResult,
  VariantMatchOverrideIdentitySnapshot,
  VariantMatchOverride,
  ApplyVariantMatchOverridesResult,
} from './internal/multi-qaf/variant-matcher'

// ── Multi-QAF Container-Level-Vergleich (KAR-937/Multi-QAF-Programm P2.3)
// ────────────────────────────────────────────────────────────────────────
// Structural (never value-level — see internal/multi-qaf/container-differ.ts
// module header for the exact P2.4/P2.5/P2.6 scope boundary) comparison of
// two finished MultiQafContainer objects (diffContainers), given an
// already-computed variant-matcher.ts matchResult. Master-Prompt §14: "must
// not be reduced to a list of cell differences" — separate, evidence-
// carrying finding groups for variants/dimensions/shared-material/profiles/
// template. No ingest/UI wiring in this PR (comes with the P2-compare-flow
// once P2.4-2.6 land).
export { allMultiQafContainerVariants, detailLinkageStatus, diffContainers } from './internal/multi-qaf/container-differ'
export type {
  VariantIdentityRef,
  VariantDimensionValueChange,
  VariantAddedFinding,
  VariantRemovedFinding,
  VariantRenamedFinding,
  VariantReorderedFinding,
  VariantActiveStateChangeFinding,
  DetailLinkageStatus,
  DetailLinkageEvidence,
  VariantDetailLinkageTransition,
  DetailWithoutSummarySetDiff,
  SummaryWithoutDetailFinding,
  MultiQafVariantContainerDiff,
  VariantDimensionKeyDiff,
  SharedMaterialRowIdentityRef,
  SharedMaterialRowChangedFinding,
  SharedMaterialStructureDiff,
  MultiQafSharedMaterialContainerDiff,
  ProfileIdentityRef,
  ProfileValueMetadataChange,
  VolumeBandThresholdChangeFinding,
  ProfileBindingChangeFinding,
  MultiQafProfileContainerDiff,
  TemplateFamilyDiff,
  SheetSetDiff,
  NotTrackedFact,
  MultiQafTemplateContainerDiff,
  MultiQafContainerDiffOptions,
  MultiQafContainerDiff,
} from './internal/multi-qaf/container-differ'

// ── Multi-QAF zweistufiger Material-Vergleich (KAR-938/Multi-QAF-Programm
// P2.4) ────────────────────────────────────────────────────────────────────
// Master-Prompt §11 "the material comparison must operate at two levels" —
// diffMaterial(alt, neu, matchResult) compares the same
// container.sharedMaterialMaster container-differ.ts (P2.3) diffs, but at the
// VALUE level that module explicitly, deliberately leaves out: 11.1
// shared-component-level field changes (unit cost value/currency, exchange
// rate, logistics/duty, material overhead, formula, row identity) and 11.2
// variant-allocation-level changes (quantity-factor change, inclusion/
// exclusion, added/removed component, substitution suspicion) — one shared
// change reported as ONE finding with its affected variants and per-variant
// commercial impact, never duplicated per variant (see internal/multi-qaf/
// material-differ.ts module header for the full KERN-REGEL/Mixed-Currency-
// Doktrin/fail-closed design). No ingest/UI wiring in this PR.
export { DEFAULT_MATERIAL_DIFFER_CONFIG, diffMaterial } from './internal/multi-qaf/material-differ'
export type {
  MaterialDifferConfig,
  MaterialComponentRef,
  VariantImpactUncomputableReason,
  VariantImpact,
  MaterialImpactAggregate,
  SharedComponentImpactSummary,
  UnitCostValueChangeFinding,
  UnitCostCurrencyChangeFinding,
  ExchangeRateChangeFinding,
  MoneyFieldKind,
  MoneyFieldChangeFinding,
  FormulaChangeFinding,
  RowIdentityChangeFinding,
  MaterialSharedComponentDiff,
  VariantAllocationChangeKind,
  VariantAllocationFinding,
  SubstitutionSuspectedFinding,
  MaterialVariantAllocationDiff,
  MaterialDiffOptions,
  MaterialDiffResult,
} from './internal/multi-qaf/material-differ'

// ── Multi-QAF Rekonziliation je VirtualQafVariant (KAR-940/Multi-QAF-Programm
// P2.6, the LAST P2 item) ───────────────────────────────────────────────────
// Master-Prompt §13: unlike container-differ.ts/material-differ.ts/
// profile-differ.ts above (all ALT vs NEU), this module verifies the
// INTERNAL consistency of a SINGLE MultiQafContainer — reconcileContainer(
// container) / reconcileVirtualVariant(variant, container) return one
// bestanden/abweichung/nicht_pruefbar check per §13 item per variant. See
// internal/multi-qaf/variant-reconciliation.ts module header for the full,
// honest per-check coverage matrix (which checks have a genuinely
// independent second source today vs. which are structurally same-source or
// missing — most are, by design, never a fake 'bestanden'). No ingest/UI
// wiring in this PR (the P2-compare-flow that wires P2.1-2.6 together is the
// FIRST P3 item).
export { ALL_VARIANT_RECONCILIATION_CHECK_IDS, reconcileContainer, reconcileVirtualVariant } from './internal/multi-qaf/variant-reconciliation'
export type {
  VariantReconciliationStatus,
  VariantReconciliationNichtPruefbarReason,
  VariantReconciliationCheckId,
  VariantReconciliationToleranceBand,
  VariantReconciliationCheck,
  VariantReconciliationResult,
} from './internal/multi-qaf/variant-reconciliation'

// ── Multi-QAF Fertigungs-/Rüst-Profil-Vergleich (KAR-939/Multi-QAF-Programm
// P2.5) ─────────────────────────────────────────────────────────────────────
// Master-Prompt §12's 8 separate finding groups (Fertigungsprozess-,
// Profiltotal-, Bindungs-Wert-, Neu-/Entfernt-, Inkonsistente-Bindung-,
// Summary-Reconciliation-Befunde) — the VALUE-level counterpart to
// container-differ.ts's own (structural-only) `profiles.*` fields. See
// internal/multi-qaf/profile-differ.ts module header for the exact #309/#310
// boundary (who reports what, no double-reporting). Not re-exported until
// KAR-942/P3.1 (compare-flow.ts, the first caller) — this was a genuine gap:
// every other P2 differ module (container-differ.ts/material-differ.ts) was
// already barrel-exported.
export { DEFAULT_PROFILE_DIFFER_CONFIG, reconciliationEntries, diffProfiles } from './internal/multi-qaf/profile-differ'
export type {
  ProfileDifferConfig,
  ProfileDiffOptions,
  ProfileBindingBucket,
  ProfileValueEntry,
  ProfileComponentValueChangedFinding,
  ProfileTotalChangedFinding,
  ProfileBindingDirection,
  ProfileBindingCurrencyState,
  ProfileBindingValueImpactFinding,
  ProfileWithValuesRef,
  InconsistentBindingReason,
  InconsistentBindingEntry,
  InconsistentBindingSetDiff,
  SummaryReconciliationStatus,
  SummaryReconciliationNichtPruefbarReason,
  SummaryReconciliationCachedValueDrift,
  SummaryReconciliationEntry,
  SummaryReconciliationChangedEntry,
  SummaryReconciliationSetDiff,
  ProfileDiffResult,
} from './internal/multi-qaf/profile-differ'

// ── Multi-QAF Compare-Flow MQ<->MQ end-to-end (KAR-942/Multi-QAF-Programm
// P3.1, the FIRST P3 item) ──────────────────────────────────────────────────
// Orchestrates every P2 module above (variant-matcher.ts's matchVariants/
// matchVariantsWithOverrides, container-differ.ts's diffContainers,
// material-differ.ts's diffMaterial, profile-differ.ts's diffProfiles,
// variant-reconciliation.ts's reconcileContainer per side) into ONE composed,
// versioned, JSON-serializable MultiQafComparisonResult — see internal/
// multi-qaf/compare-flow.ts module header for the full pipeline, the
// VariantMatchOverride persistence design, and the qaf_comparison.
// engine_version/baseline_status persistence shape actions.ts's wiring uses.
export {
  MULTI_QAF_COMPARISON_RESULT_VERSION,
  runMultiQafCompareFlow,
  multiQafBaselineStatusFor,
  serializeMultiQafComparisonResult,
  deserializeMultiQafComparisonResult,
} from './internal/multi-qaf/compare-flow'
export type { MultiQafComparisonResult, RunMultiQafCompareFlowOptions } from './internal/multi-qaf/compare-flow'

// ── Multi-QAF Aggregat-Impact mit Validitäts-Gates (KAR-944/Multi-QAF-
// Programm P3.3, the LAST P3 item) ──────────────────────────────────────────
// Master-Prompt §19 "only calculate an aggregate Multi-QAF impact when the
// basis is valid" — computeAggregateImpact runs 6 named gates
// (compatible_currencies/volumes_available/no_duplicates_or_ambiguous/
// consistent_units/valid_baseline/no_blocked_critical_mappings) over an
// already-computed matchResult/materialDiff/profileDiff/containerDiff/
// reconciliation, and only THEN sums a per-currency annual/lifetime impact
// over the included population — every excluded variant carries its own
// reason (never silently dropped). Not previously barrel-exported (KAR-947
// is its first UI/re-export consumer — compare-flow.ts's own
// runMultiQafCompareFlow already calls it directly via a relative import,
// same "not barrel-exported until a caller outside multi-qaf/ needs it"
// discipline profile-differ.ts's own history documents). See internal/
// multi-qaf/aggregate-impact.ts module header for the full gate/exclusion/
// Buckets-Doktrin design.
export { AGGREGATE_IMPACT_RESULT_VERSION, computeAggregateImpact } from './internal/multi-qaf/aggregate-impact'
export type {
  AggregateImpactGateId,
  AggregateImpactGateOutcome,
  AggregateImpactExclusionReason,
  AggregateImpactExclusion,
  VariantUnitPriceDeltaSource,
  VariantUnitPriceDeltaComponent,
  CurrencyBucket,
  VariantUnitPriceDelta,
  VariantTimeframeImpact,
  AggregateImpactCurrencyTotal,
  AggregateImpactTimeframe,
  AggregateImpactStructuralFallback,
  AggregateImpactAssumption,
  AggregateImpactResult,
  AggregateImpactInputs,
  AggregateImpactOptions,
} from './internal/multi-qaf/aggregate-impact'

// ── Multi-QAF Summary-Kennzahlen-Diff je Variante (KAR-951, urgent livetest
// fix) ───────────────────────────────────────────────────────────────────
// Diffs `VirtualVariantSummaryTotals` ALT<->NEU per matched variant pair —
// the missing diff the KAR-951 livetest exposed (a Multi-QAF pair where only
// 2 global Summary-sheet surcharge parameters changed produced ZERO findings
// anywhere, even though every variant's computed Summary total moved). A
// PEER of materialDiff/profileDiff on `MultiQafComparisonResult`
// (compare-flow.ts `summaryTotalsDiff` field) — see summary-totals-differ.ts
// module header for the full "§19 boundary" (never merged into
// aggregateImpact above) and Mixed-Currency-Doktrin.
export { DEFAULT_SUMMARY_TOTALS_DIFFER_CONFIG, diffSummaryTotals, SUMMARY_TOTALS_METRIC_KEYS } from './internal/multi-qaf/summary-totals-differ'
export type {
  SummaryTotalsDifferConfig,
  SummaryTotalsDiffOptions,
  SummaryTotalsMetricKey,
  SummaryTotalsMetricState,
  SummaryTotalsCurrencyGate,
  SummaryTotalsMissingSide,
  SummaryTotalsMetricFinding,
  SummaryTotalsMaterialCurrencyFinding,
  SummaryTotalsCurrencySum,
  SummaryTotalsDiffResult,
} from './internal/multi-qaf/summary-totals-differ'

// ── Multi-QAF-Variante <-> Standard-QAF-Vergleich (KAR-943/Multi-QAF-Programm
// P3.2, Master-Prompt §15 Szenario B) ───────────────────────────────────────
// EINE explizit gewählte, aktive Multi-QAF-Variante durch die bestehende
// Standard-Vergleichs-Engine geschickt (Summary-Identität + SummaryMetrics
// real, alles Prozesszeilen-basierte ehrlich degradiert) — see internal/
// multi-qaf/variant-vs-standard.ts module header for the full
// Modul-Bedienbarkeits-Matrix and the fail-closed variant-selection contract.
export {
  MULTI_QAF_VARIANT_VS_STANDARD_RESULT_VERSION,
  DEGRADED_MODULES,
  runVariantVsStandardCompare,
  checkVariantVsStandardIdentity,
  hasCriticalIdentityIssue,
  serializeVariantVsStandardComparisonResult,
  deserializeVariantVsStandardComparisonResult,
} from './internal/multi-qaf/variant-vs-standard'
export type {
  VariantVsStandardComparisonResult,
  VariantVsStandardDegradedModuleFinding,
  VariantVsStandardDegradedModuleKey,
  VariantVsStandardReviewRequiredReason,
  RunVariantVsStandardCompareOptions,
} from './internal/multi-qaf/variant-vs-standard'

// ── Multi-QAF / Variante↔Standard XLSX export (KAR-949) ─────────────────────
// Sibling to ./internal/export.ts's buildQafExportWorkbook (Standard) and
// ./internal/g60/export.ts's buildG60ExportWorkbook (G60) — see
// internal/multi-qaf/export.ts module header for the full sheet design and
// the "never touches those two files" byte-identity guarantee.
export { buildMultiQafExportWorkbook, buildVariantVsStandardExportWorkbook } from './internal/multi-qaf/export'
export type { MultiQafExportInput, VariantVsStandardExportInput } from './internal/multi-qaf/export'

// ── Comparison-mode dispatch registry (KAR-943 adversarial-review F2) ──────
// Single source of truth for "what does comparison_mode X expect at each
// dispatch point (file-kind guard, export support, pins/swap applicability)"
// — see internal/comparison-mode.ts module header. Lives outside
// app/qaf-differences/actions.ts because that file is `'use server'`
// (every top-level export there must be an async Server Action).
export {
  COMPARISON_MODE_RULES,
  normalizeComparisonMode,
  comparisonModeRule,
} from './internal/comparison-mode'
export type { QafComparisonModeKey, ComparisonModeRule, IngestedQafFileKind } from './internal/comparison-mode'

// ── Capability-Kern (KAR-959/P2, Master-Prompt §11-§17 + §31-§32) ──────────
// Architectural fundament for the QAF-Corpus-Generalization-Programme (Epic
// KAR-957) — replaces gate-audit.md's 17 blocking template-gates with
// capability-based logic. See internal/capability/*.ts module headers for
// the individual components; module-capability-resolver.ts is the §32
// gate-replacement API surface a future P3/P4 migrates the actual gates onto
// (this PR ships the API only, the gates themselves are untouched).
export { resolveSheetRole, resolveSheetRoles, sheetForRole, SHEET_RESOLVER_ASSUMPTIONS, NAME_SIGNAL_MAX_CONFIDENCE } from './internal/capability/sheet-resolver'
export {
  CAPABILITY_FIELDS,
  deriveFieldScope,
  fieldsForModule,
  fieldsByScope,
  findFieldByAlias,
  moduleSheetRole,
} from './internal/capability/field-registry'
export type { CapabilityFieldScopeKind, CapabilityFieldRegistryEntry } from './internal/capability/field-registry'
// KAR-960/P3: the §14 FieldCandidateCollector/FieldConflictResolver pipeline
// (KAR-959/P2 review finding #3, PR #326) now HAS production producers —
// manufacturing-field-candidates.ts (Hebel A) and summary-field-candidates.ts
// (Hebel B), wired into workbook-adapter.ts's parseQafFile/parseSummarySheet
// — so the resolver + its types are re-exported here alongside the first
// real consumer (app/qaf-differences/comparison-meta-actions.ts's getCalculatorParams +
// app/qaf-differences/[id]/page.tsx's Produktionssicht/Anomalien sections).
export {
  collectFieldCandidates,
  resolveFieldCandidates,
  resolveAllFieldCandidates,
  rankFieldCandidates,
  candidateValuesEqual,
  CANDIDATE_VALUE_RELATIVE_TOLERANCE,
} from './internal/capability/field-candidates'
export type { FieldScope, ScopedValue, FieldCandidate, FieldConflictStatus, FieldResolution } from './internal/capability/types'
export {
  manufacturingStepFieldCandidates,
  PROCESS_PARAMETER_FIELD_KEYS,
} from './internal/capability/manufacturing-field-candidates'
export {
  summaryMasterRateFieldCandidates,
  summaryTotalsFieldCandidates,
  summaryFieldCandidates,
  SUMMARY_TOTALS_CANDIDATE_METRIC_KEYS,
  MASTER_RATE_LABEL_SCAN_CONFIDENCE,
} from './internal/capability/summary-field-candidates'
// KAR-960/P3 — Produktionssicht/Anomalien view-model builders (Gate-Audit
// Top-5 #5, Master-Prompt §22/§23). Consumed by qaf-comparison-detail.tsx.
// KAR-966 adds scenarioAvailability (item 2, capability-gated Szenario-
// Editor hint) and productionFieldDelta (item 3, Produktionssicht diff
// highlight) — same module, same evidence-based §23 principle.
export {
  buildProductionRateRows,
  productionViewAvailability,
  buildMasterRateRows,
  anomaliesAvailability,
  scenarioAvailability,
  productionFieldDelta,
} from './internal/capability/production-view'
export type {
  ProductionStepRates,
  ProductionRateRow,
  StepRowLike,
  SectionAvailability,
  MasterRateSideValue,
  MasterRateRow,
  ProductionFieldDeltaKind,
} from './internal/capability/production-view'
// KAR-960/P3 — Preis-Kalkulator bridge for Summary-mode comparisons (task
// instruction 3a). Consumed by app/qaf-differences/actions.ts's
// getCalculatorParams.
export {
  calculatorParamsFromSummaryStep,
  summaryCalculatorStepOptions,
  // KAR-966 item 1: speaking Preis-Kalkulator dropdown label per step VALUE
  // (kept separate from summaryCalculatorStepOptions's lookup-key contract).
  summaryCalculatorStepLabels,
  EMPTY_SUMMARY_MASTER_RATES,
} from './internal/capability/calculator-bridge'
export type { SummaryCalculatorSideParams, SummaryMasterRates } from './internal/capability/calculator-bridge'
export {
  detectWorkbookCapabilities,
  computeWorkbookCapabilityMatrix,
  facetSignalFromRowArray,
  facetSignalFromSingleRecord,
  facetSignalFromManufacturingSteps,
  facetSignalFromSummary,
  AVAILABLE_CONFIDENCE_THRESHOLD,
} from './internal/capability/capability-detector'
export type { FacetParseSignal, WorkbookCapabilityInput } from './internal/capability/capability-detector'
export {
  moduleCapability,
  isModuleAvailable,
  isModuleUsable,
  availableModules,
  usableModules,
  shouldShowSection,
  summarizeCoverage,
} from './internal/capability/module-capability-resolver'
export type { CapabilityCoverageSummary } from './internal/capability/module-capability-resolver'
export { CAPABILITY_MODULES, CAPABILITY_MODEL_VERSION } from './internal/capability/types'
export type {
  SheetRole,
  SheetRoleAssignment,
  CapabilityStatus,
  CapabilitySource,
  ModuleCapability,
  WorkbookCapabilityMatrix,
} from './internal/capability/types'
// FieldScope/ScopedValue/FieldCandidate/FieldConflictStatus/FieldResolution
// stay internal-only — see the field-candidates NOTE above (KAR-959 review
// finding #3, PR #326).
// KAR-961/P4 — "Umlageschema-Kalkulation" template family onboarding
// (gate-audit.md capability-matrix.md finding #3). See
// cost-allocation-family.ts module header for scope/confidentiality
// discipline. Consumed by app/qaf-differences/actions.ts's ingest path
// (additive g60_meta.costAllocationFamily JSONB bag, same pattern as
// templateFingerprint/multiQafDetection above — no schema change).
export {
  detectCostAllocationFamily,
  resolveCostAllocationSheetRoles,
  extractCostAllocationMeta,
  buildCostAllocationCapabilityMatrix,
  COST_ALLOCATION_FAMILY_ID,
  COST_ALLOCATION_FAMILY_PROFILES,
} from './internal/capability/cost-allocation-family'
export type {
  CostAllocationSubProfile,
  CostAllocationFamilyProfile,
  CostAllocationFamilySheets,
  CostAllocationFamilyDetection,
  CostAllocationMetaField,
  CostAllocationMetaKey,
} from './internal/capability/cost-allocation-family'
// KAR-962/P5 — not-a-QAF detection + minimal UnknownPatternCollector
// (Master-Prompt §30, task scope point 3). See not-a-qaf-detector.ts module
// header for the full design (why structural, not filename/hash-based; why a
// SUSPECTED warning, not a hard reject). Consumed by
// app/qaf-differences/actions.ts's ingest path (additive g60_meta.notAQaf
// JSONB bag, same pattern as costAllocationFamily above) and by
// compare.ts-adjacent comparison assembly (notAQafToPlausibilityIssue, same
// PlausibilityIssue-channel-reuse pattern as templateFingerprintToPlausibilityIssue).
export { detectNotAQaf, notAQafToPlausibilityIssue, collectUnknownPattern, structuralPatternFingerprint } from './internal/capability/not-a-qaf-detector'
export type { NotAQafDetection, UnknownPatternRecord } from './internal/capability/not-a-qaf-detector'

// V2-Envelope (Spec Kap. 6/13/20) — Engine-Kennung, Konventionen,
// Vergleichstyp-Ableitung und Sektionszustand.
export { QAF_COMPARE_ENGINE, QAF_CONVENTIONS, deriveComparisonType, sectionStateOf } from './internal/export-envelope'
export type {
  QafComparisonType,
  ComparisonTypeBasis,
  ComparisonTypeVerdict,
  ComparisonIdentity,
  SectionStatus,
  SectionState,
  QafConventions,
} from './internal/export-envelope'

// Kanonische Serialisierung + Determinismus-Hash (Kap. 10, R-17/R-19).
export { canonicalNumber, canonicalizeNumbers, hashableDocument, contentHash } from './internal/export-canonical'
// Validierungs-Sektion (Kap. 7.8, R-14).
export { buildValidation } from './internal/export-validation'
export type { ValidationCheck, ValidationResult, ValidationInput, CheckStatus } from './internal/export-validation'

// summary_lines — Preisblock-Zeilen mit Rolle, Block, Einheit, Label-Stand (Kap. 7.2).
export { buildSummaryLines } from './internal/summary-view'
export type { SummaryLine } from './internal/summary-view'

// Zeilenrollen-Registry des Preisblocks (R-05/R-07).
export { SUMMARY_ROW_REGISTRY, additiveRowSpecs, roleOfMetric, registrySpecFor } from './internal/summary-row-registry'
export type { SummaryRowRole, SummaryRowSpec, SummaryLabelSource } from './internal/summary-row-registry'

// Material-Positionsmapping (Kap. 7.3/8.3/8.4) — Phase 2.
export { normalizeMaterialName, namesMatch, tokenOverlap } from './internal/material-name'
export type { NormalizedName } from './internal/material-name'
export { buildMaterialMappings } from './internal/material-mapping'
export type {
  MaterialMatchType,
  MappablePosition,
  MaterialMapping,
  MaterialMappingResult,
} from './internal/material-mapping'
export { classifyMaterialEffects } from './internal/material-mapping'
export type { MaterialEffectBucket, ClassifiedMapping, MaterialEffectResult } from './internal/material-mapping'

// Fertigung: Stationsbegriff, Takt, Kapazität (Kap. 7.4/8.8, R-10).
export { classifyRows, computeTakt, computeCapacity, stationsOverPeak } from './internal/manufacturing-stations'
export type { ManufacturingRow, ClassifiedRow, RowKind, Takt, TaktInput, StationCapacity } from './internal/manufacturing-stations'

// Fertigung: Stationsmapping und Parameteridentität (Kap. 7.4, R-10/R-16).
export { mapStations, parametersIdentical } from './internal/manufacturing-mapping'
export type {
  MappableStation,
  StationParameters,
  StationMatchType,
  StationMapping,
  StationMappingResult,
} from './internal/manufacturing-mapping'

// Fertigung: unabhängige Nachrechnung der Stationskosten (Kap. 7.4, D06).
export { computeStationCost, checkStationCost, checkAllStationCosts } from './internal/manufacturing-cost-check'
export type { StationCostInputs, StationCostBreakdown, StationCostCheck, CostCheckStatus, CostCheckSummary } from './internal/manufacturing-cost-check'

// Fertigung: verlagerte Untervorgänge und die Zeitgutschrift-Frage (Kap. 7.4).
export { diffSubOperations, timeCreditQuestion } from './internal/manufacturing-sub-operations'
export type { SubOperation, SubOperationDiff, TimeCreditQuestion } from './internal/manufacturing-sub-operations'

// ── Loop 13: AI-Paket und Antwort-Wächter (KI- und Aria-Schicht) ─────────────
export {
  AI_PROMPT_VERSION,
  AI_SYSTEM_PROMPT_DE,
  buildAiPackage,
  validateAiSummary,
  zahlenInAntwort,
} from './internal/ai-package'
export type { AiPackage, AiPackageResult, AiSummaryProblem } from './internal/ai-package'

// ── Loop 12: EIN Versionsregister für alle Exportprofile ─────────────────────
export {
  EXPORT_PROFILES,
  exportProfileStamp,
  exportProfileStampLineDe,
} from './internal/export-profiles'
export type { ExportProfileId, ExportProfileStamp } from './internal/export-profiles'
