'use client' import { useCallback, useRef, useState } from 'react' import type { AdvisorEvidenceMeta } from '@/lib/sdk/advisor/evidence' import { emptyStats } from '@/lib/sdk/advisor/evidence' export interface AdvisorTurn { id: string question: string answer: string meta: AdvisorEvidenceMeta status: 'streaming' | 'done' | 'error' error?: string } function emptyMeta(): AdvisorEvidenceMeta { return { stats: emptyStats(), sources: [], figures: [], footnotes: [] } } interface UseAdvisorStreamArgs { currentStep: string country: string } /** * Drives the Evidence Workspace: posts a question, parses the FIRST line of the response as * structured `AdvisorEvidenceMeta`, then streams the remaining bytes as the markdown answer. * The answer text is NEVER parsed for structure — sources/figures/footnotes come from the meta. */ export function useAdvisorStream({ currentStep, country }: UseAdvisorStreamArgs) { const [turns, setTurns] = useState([]) const [isStreaming, setIsStreaming] = useState(false) const abortRef = useRef(null) const patch = useCallback((id: string, p: Partial) => { setTurns((prev) => prev.map((t) => (t.id === id ? { ...t, ...p } : t))) }, []) const stop = useCallback(() => { abortRef.current?.abort() setIsStreaming(false) }, []) const send = useCallback( async (question: string) => { const q = question.trim() if (!q || isStreaming) return const id = `turn-${Date.now()}` const history = turns.flatMap((t) => [ { role: 'user', content: t.question }, { role: 'assistant', content: t.answer }, ]) setTurns((prev) => [...prev, { id, question: q, answer: '', meta: emptyMeta(), status: 'streaming' }]) setIsStreaming(true) abortRef.current = new AbortController() try { const res = await fetch('/api/sdk/compliance-advisor/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: q, history, currentStep, country }), signal: abortRef.current.signal, }) if (!res.ok || !res.body) { const e = await res.json().catch(() => ({ error: 'Unbekannter Fehler' })) throw new Error(e.error || `Server-Fehler (${res.status})`) } const reader = res.body.getReader() const decoder = new TextDecoder() let buf = '' let metaEnd = -1 let meta: AdvisorEvidenceMeta | null = null for (;;) { const { done, value } = await reader.read() if (done) break buf += decoder.decode(value, { stream: true }) if (metaEnd === -1) { const nl = buf.indexOf('\n') if (nl === -1) continue metaEnd = nl + 1 try { meta = JSON.parse(buf.slice(0, nl)) as AdvisorEvidenceMeta } catch { meta = null // no valid meta -> treat whole stream as answer metaEnd = 0 } } patch(id, { answer: buf.slice(metaEnd), ...(meta ? { meta } : {}) }) } buf += decoder.decode() patch(id, { answer: buf.slice(metaEnd === -1 ? 0 : metaEnd), status: 'done', ...(meta ? { meta } : {}) }) setIsStreaming(false) } catch (err) { setIsStreaming(false) if ((err as Error).name === 'AbortError') { patch(id, { status: 'done' }) return } patch(id, { status: 'error', error: err instanceof Error ? err.message : 'Verbindung fehlgeschlagen' }) } }, [isStreaming, turns, currentStep, country, patch], ) return { turns, isStreaming, send, stop } }