/**
 * Manufacturing-capability assessment (QVS-P1, KAR-970).
 *
 * Pure function over already-parsed `QAFRow[]` — no DB access (P2 wires this
 * to `qaf_file.id` / `qaf_manufacturing_step`, see
 * reports/qaf-value-stream-architecture.md §2 service table). Eligibility is
 * capability-based, not template-based: any row with a non-blank
 * `prozessbezeichnung` counts, regardless of which sheet/template family it
 * came from (no G60/INPUT template requirement).
 */

import { type QAFFieldKey, type QAFParseMeta, type QAFRow } from '@/lib/qaf-parser'
import { PRIMARY_FIELD_MAPPINGS } from './mapper'
import type { CapabilityAssessment, QvsWarning } from './types'

export function assessManufacturingCapability(rows: QAFRow[], parseMeta?: QAFParseMeta): CapabilityAssessment {
  const eligibleRows = rows.filter((row) => row.prozessbezeichnung?.trim())
  const stepCount = eligibleRows.length
  const warnings: QvsWarning[] = []

  const fieldCoverage: Partial<Record<QAFFieldKey, number>> = {}
  if (stepCount > 0) {
    for (const { source } of PRIMARY_FIELD_MAPPINGS) {
      const withValue = eligibleRows.filter((row) => hasValue(row, source)).length
      fieldCoverage[source] = withValue / stepCount
    }
  }

  if (rows.length > 0 && stepCount === 0) {
    warnings.push({
      code: 'no_eligible_rows',
      message: 'Alle geparsten Zeilen haben keine Prozessbezeichnung — Datei enthält keine bewertbaren Fertigungsschritte.',
    })
  }

  // parseMeta is currently informational-only for the capability assessment
  // (no field of CapabilityAssessment reads it yet) — accepted per the P1
  // signature contract so callers already have a stable API once P2 wires a
  // richer assessment (e.g. degrading eligibility on very low
  // parseConfidence). Referenced here only to keep the parameter used.
  void parseMeta

  return { eligible: stepCount > 0, stepCount, fieldCoverage, warnings }
}

function hasValue(row: QAFRow, key: QAFFieldKey): boolean {
  const value = row[key]
  return typeof value === 'string' ? value.trim() !== '' : value !== null && value !== undefined
}
