'use client'

import { useEffect, useState } from 'react'

export interface ArchStage {
  id: string
  title: string
  summary: string
  input: string
  logic: string
  data_source: string
  example: string
}

export interface ArchLibrary {
  name: string
  count: number
  source_file: string
  description: string
}

export interface ArchDataSource {
  name: string
  license: string
  usage: string
  status: string // "verwendet" | "ausgeschlossen"
}

export interface RiskEvidence {
  mode: string
  label: string
  stat: string
  source: string
  license: string
  attribution: string
  retrieved: string
}

export interface Architecture {
  stages: ArchStage[]
  libraries: ArchLibrary[]
  data_sources: ArchDataSource[]
  norm_matching: string[]
  evidence: RiskEvidence[]
}

/** Loads the data-driven IACE engine self-description (global, not per project). */
export function useArchitecture() {
  const [data, setData] = useState<Architecture | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      try {
        const res = await fetch('/api/sdk/v1/iace/architecture')
        const json = res.ok ? ((await res.json()) as Architecture) : null
        if (!cancelled) setData(json)
      } catch (err) {
        console.error('Failed to load IACE architecture:', err)
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    load()
    return () => {
      cancelled = true
    }
  }, [])

  return { data, loading }
}
