// Cyber-meets-CE: derive cyber-defeatable safety functions from an IACE project's
// real hazards + mitigations, to feed the CRA cross-link bridge (replaces the demo
// hardcode). Only control-dependent hazards (movement/actuation, signal-integrity)
// can be re-opened by a cyber attack — purely physical ones (thermal, sharp edges,
// noise) are excluded. Mirrors the backend cra_safety_bridge kinds.

export interface IaceHazard {
  id: string
  name: string
  description?: string
  category: string
  possible_harm?: string
}
export interface IaceMitigation {
  id: string
  name: string
  reduction_type?: string
  linked_hazard_ids?: string[]
}
export interface SafetyFunction {
  name: string
  hazard: string
  original_measure: string
  kind: string
}

// IACE hazard category -> the cyber-bridge safety-function kind.
const KIND_BY_CATEGORY: Record<string, string> = {
  // control-driven movement/actuation: a cyber attack can trigger it
  mechanical_hazard: 'prevent_unexpected_actuation',
  mechanical: 'prevent_unexpected_actuation',
  crush: 'prevent_unexpected_actuation',
  crush_point: 'prevent_unexpected_actuation',
  crushing: 'prevent_unexpected_actuation',
  movement: 'prevent_unexpected_actuation',
  pneumatic_hydraulic: 'prevent_unexpected_actuation',
  safety_function_failure: 'prevent_unexpected_actuation',
  software_control: 'prevent_unexpected_actuation',
  software_fault: 'prevent_unexpected_actuation',
  // sensor/signal/parameter integrity: a cyber attack can corrupt it
  signal: 'signal_integrity',
  signale: 'signal_integrity',
  sensor_spoofing: 'signal_integrity',
  communication_failure: 'signal_integrity',
  configuration_error: 'signal_integrity',
}

export function deriveSafetyFunctions(hazards: IaceHazard[], mitigations: IaceMitigation[]): SafetyFunction[] {
  const measuresByHazard: Record<string, string[]> = {}
  for (const m of mitigations || []) {
    for (const hid of m.linked_hazard_ids || []) {
      (measuresByHazard[hid] ||= []).push(m.name)
    }
  }
  const out: SafetyFunction[] = []
  for (const h of hazards || []) {
    const kind = KIND_BY_CATEGORY[h.category]
    if (!kind) continue
    out.push({
      name: h.name,
      hazard: h.possible_harm || h.description || h.name,
      original_measure: (measuresByHazard[h.id] || []).join(', ') || 'IACE-Schutzmaßnahme',
      kind,
    })
  }
  return out
}

// Fetch the project's hazards + mitigations and derive the cyber-relevant safety
// functions. Returns [] on any error (caller falls back to its demo functions).
export async function fetchProjectSafetyFunctions(projectId: string): Promise<SafetyFunction[]> {
  try {
    const [hRes, mRes] = await Promise.all([
      fetch(`/api/sdk/v1/iace/projects/${projectId}/hazards`),
      fetch(`/api/sdk/v1/iace/projects/${projectId}/mitigations`),
    ])
    const hJson = hRes.ok ? await hRes.json() : {}
    const mJson = mRes.ok ? await mRes.json() : {}
    const hazards: IaceHazard[] = hJson.hazards || (Array.isArray(hJson) ? hJson : [])
    const mitigations: IaceMitigation[] = mJson.mitigations || (Array.isArray(mJson) ? mJson : [])
    return deriveSafetyFunctions(hazards, mitigations)
  } catch {
    return []
  }
}
