/**
 * Conservative value-added classification (QVS-P1, KAR-970).
 *
 * `conservativeVaClass(processName)` NEVER returns 'va' automatically — the
 * Excel-import precedent this program explicitly breaks with hardcoded
 * `isValueAdded=true` on every imported step (architecture.md §2 va-
 * classification row). Only three conservative buckets are pattern-matched
 * (transport/logistics, rework, storage → 'nva'; inspection/measurement/
 * control → 'nnva'); everything else is 'unknown' — including obviously
 * value-adding-sounding names like "Schweißen" (welding) or "Montieren"
 * (assembling). A human (or a future, evidence-backed rule) decides 'va',
 * never this function.
 *
 * Patterns are case-insensitive substrings, not `\b`-anchored whole-word
 * matches: German compounds concatenate freely ("Transportsicherung",
 * "Zwischenlagerung", "Sichtprüfung", "Endkontrolle") so a strict word-start
 * boundary would miss real hits. The one deliberately narrowed pattern is
 * the "mess" (measure) root — a bare substring would also match "Messer"
 * (knife) and "Messe" (trade fair), so it requires one of the actual
 * measure-verb/noun suffixes (see NNVA_PATTERNS below + the negative test
 * cases in va-classification.test.ts).
 */

import type { VaClass } from '@/lib/vsm-types'

// Checked first: prüf/mess/inspektion/kontrolle (DE) + inspect/measure/
// check/"quality control" (EN) → 'nnva'.
const NNVA_PATTERNS: readonly RegExp[] = [
  /prüf/i,
  /inspekt/i,
  /inspect/i,
  // "mess" root narrowed to actual measure-verb/noun forms — excludes
  // "Messer" (knife) / "Messe" (trade fair), see module header. Boundary
  // group spelled out explicitly (not relying on /i case-folding umlauts
  // inside a character class, which is inconsistent across engines).
  /(^|[^a-zA-ZäöüÄÖÜß])(ver|aus|nach)?mess(en|ung|ungen|ger[äÄa]t|platz|mittel|stelle)/i,
  /\bmeasure(ment)?/i,
  /kontroll/i,
  /quality\s*control/i,
  /\bcheck(ing)?\b/i,
]

// Checked second: transport/logistik, nacharbeit/rework, lager/puffer/storage → 'nva'.
const NVA_PATTERNS: readonly RegExp[] = [
  /transport/i,
  /logistik/i,
  /logistic/i,
  /nacharbeit/i,
  /rework/i,
  /lager/i,
  /puffer/i,
  /storage/i,
]

/**
 * Classify a process name conservatively. Precedence when a name matches
 * both groups (e.g. "Transport zur Prüfung"): nnva wins — locked in by a
 * test in va-classification.test.ts. Never returns 'va'.
 */
export function conservativeVaClass(processName: string | null | undefined): VaClass {
  const name = (processName ?? '').trim()
  if (!name) return 'unknown'
  if (NNVA_PATTERNS.some((re) => re.test(name))) return 'nnva'
  if (NVA_PATTERNS.some((re) => re.test(name))) return 'nva'
  return 'unknown'
}
