export type PresenceStatus = 'vorhanden' | 'nicht_vorhanden' | 'geloescht'

export interface Component {
  id: string
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  // is_safety_relevant is the backend's field name (the form's `safety_relevant`
  // does not currently round-trip). Read this when deriving CE obligations.
  is_safety_relevant?: boolean
  // ce_marked: bought component carrying its own CE / DoC (robot, actuator, SPS).
  // Safe semantics — no hazard suppression; drives provenance + the PL/SIL
  // validation note when also safety-relevant.
  ce_marked?: boolean
  // presence_status: 'vorhanden' (default) | 'nicht_vorhanden' (engine negation
  // verdict, awaiting expert review) | 'geloescht' (soft-deleted, restorable).
  presence_status?: PresenceStatus
  parent_id: string | null
  children: Component[]
  library_component_id?: string
  energy_source_ids?: string[]
  metadata?: Record<string, unknown>
}

export interface LibraryComponent {
  id: string
  name_de: string
  name_en: string
  category: string
  description_de: string
  typical_hazard_categories: string[]
  typical_energy_sources: string[]
  maps_to_component_type: string
  tags: string[]
  sort_order: number
}

export interface EnergySource {
  id: string
  name_de: string
  name_en: string
  description_de: string
  typical_components: string[]
  typical_hazard_categories: string[]
  tags: string[]
  sort_order: number
}

export interface ComponentFormData {
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  ce_marked: boolean
  parent_id: string | null
}

export const LIBRARY_CATEGORIES: Record<string, string> = {
  mechanical: 'Mechanik',
  structural: 'Struktur',
  drive: 'Antrieb',
  hydraulic: 'Hydraulik',
  pneumatic: 'Pneumatik',
  electrical: 'Elektrik',
  control: 'Steuerung',
  sensor: 'Sensorik',
  actuator: 'Aktorik',
  safety: 'Sicherheit',
  it_network: 'IT/Netzwerk',
}

export const COMPONENT_TYPES = [
  { value: 'SW', label: 'Software (SW)' },
  { value: 'FW', label: 'Firmware (FW)' },
  { value: 'AI', label: 'KI-Modul (AI)' },
  { value: 'HMI', label: 'Mensch-Maschine-Schnittstelle (HMI)' },
  { value: 'SENSOR', label: 'Sensor' },
  { value: 'ACTUATOR', label: 'Aktor' },
  { value: 'CONTROLLER', label: 'Steuerung' },
  { value: 'NETWORK', label: 'Netzwerk' },
  { value: 'MECHANICAL', label: 'Mechanik' },
  { value: 'ELECTRICAL', label: 'Elektrik' },
  { value: 'OTHER', label: 'Sonstiges' },
]

export function buildTree(components: Component[]): Component[] {
  const map = new Map<string, Component>()
  const roots: Component[] = []

  components.forEach((c) => {
    map.set(c.id, { ...c, children: [] })
  })

  components.forEach((c) => {
    const node = map.get(c.id)!
    if (c.parent_id && map.has(c.parent_id)) {
      map.get(c.parent_id)!.children.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
}
