'use client'

import { useEffect, useState } from 'react'

export interface FailureSourceDoc {
  id: number
  title: string
  source: string
  license: string
  url: string
  used: boolean
  component: string
  failure_mode: string
  confidence: string
}

export interface FailureSources {
  generated: string
  model: string
  count: number
  documents: FailureSourceDoc[]
}

/**
 * Loads the FMEA source-document register (every document we use, with source +
 * licence). Global, not per project — the auditable provenance of the
 * failure-knowledge corpus.
 */
export function useFailureSources() {
  const [data, setData] = useState<FailureSources | null>(null)

  useEffect(() => {
    let cancelled = false
    fetch('/api/sdk/v1/iace/failure-knowledge/sources')
      .then((r) => (r.ok ? r.json() : null))
      .then((j) => {
        if (!cancelled) setData(j)
      })
      .catch((err) => console.error('Failed to load failure sources:', err))
    return () => {
      cancelled = true
    }
  }, [])

  return { data }
}
