// Negotiation levers (KAR-840, V11 section 7 — summary variant).
//
// V11 rule: for every matched process-step pair, each of four process KPIs
// with |Δ%| ≥ 5 % becomes a lever with a FIXED ask phrasing (renderSec7).
// The G60 variant (global machine-rate factor, INPUT-card drivers) follows
// with the G60 engine stage. Pure + unit-tested.

export interface LeverKpiDef {
  /** qaf_manufacturing_diff.field / QAFRow key. */
  field: string
  kpiLabel: string
  /** Fixed negotiation ask (V11 wording). */
  ask: string
}

export const LEVER_KPI_DEFS: LeverKpiDef[] = [
  { field: 'zykluszeit', kpiLabel: 'Zykluszeit', ask: 'Zykluszeit-Anstieg technisch begründen lassen (Taktung, Anlagenlayout).' },
  { field: 'mss', kpiLabel: 'Maschinenstundensatz', ask: 'MSS-Kalkulation + Benchmark offenlegen.' },
  { field: 'lohnkosten', kpiLabel: 'Lohnkosten', ask: 'Lohnsatz gegen Standort-Benchmark spiegeln.' },
  { field: 'anzahlMA', kpiLabel: 'Anzahl Mitarbeiter', ask: 'Personalveränderung gegen Zykluszeit verrechnen.' },
]

/** V11 threshold: a process-KPI delta counts as a lever from 5 % up. */
const LEVER_MIN_DELTA_PCT = 0.05

export interface LeverDiffInput {
  stepLabel: string
  field: string
  alt_value: number | null
  neu_value: number | null
  delta_percent: number | null
  /** Underlying step match requires review / is uncertain (same caveat as Tornado). */
  uncertain: boolean
}

export interface Lever {
  stepLabel: string
  kpiLabel: string
  ask: string
  alt: number | null
  neu: number | null
  deltaPercent: number
  uncertain: boolean
}

export function buildLevers(diffs: LeverDiffInput[]): Lever[] {
  const defByField = new Map(LEVER_KPI_DEFS.map((d) => [d.field, d]))
  const out: Lever[] = []
  for (const d of diffs) {
    const def = defByField.get(d.field)
    if (!def) continue
    if (d.delta_percent === null || Math.abs(d.delta_percent) < LEVER_MIN_DELTA_PCT) continue
    out.push({
      stepLabel: d.stepLabel,
      kpiLabel: def.kpiLabel,
      ask: def.ask,
      alt: d.alt_value,
      neu: d.neu_value,
      deltaPercent: d.delta_percent,
      uncertain: d.uncertain,
    })
  }
  return out
}

/**
 * True when comparable process-KPI data exists at all — distinguishes "no
 * comparable steps" from "steps compared, but every KPI delta is below 5 %"
 * for an honest empty state.
 */
export function hasLeverKpiSignal(diffs: Array<Pick<LeverDiffInput, 'field' | 'delta_percent'>>): boolean {
  const fields = new Set(LEVER_KPI_DEFS.map((d) => d.field))
  return diffs.some((d) => fields.has(d.field) && d.delta_percent !== null)
}
