'use client';
import { useState, useRef, useCallback, useEffect } from 'react';
export function useToolInstallStream(toolId) {
    const [logs, setLogs] = useState([]);
    const [status, setStatus] = useState('idle');
    const [result, setResult] = useState(null);
    const esRef = useRef(null);
    const cleanup = useCallback(() => {
        if (esRef.current) {
            esRef.current.close();
            esRef.current = null;
        }
    }, []);
    // Cleanup on unmount
    useEffect(() => cleanup, [cleanup]);
    const startInstall = useCallback(() => {
        cleanup();
        setLogs([]);
        setResult(null);
        setStatus('streaming');
        const es = new EventSource(`/api/tools/${toolId}/install/stream`);
        esRef.current = es;
        es.onmessage = (event) => {
            setLogs((prev) => [...prev, event.data]);
        };
        es.addEventListener('done', (event) => {
            const installResult = JSON.parse(event.data);
            setResult(installResult);
            setStatus(installResult.status === 'error' ? 'error' : 'done');
            cleanup();
        });
        es.onerror = () => {
            setStatus('error');
            cleanup();
        };
    }, [toolId, cleanup]);
    return { logs, status, result, startInstall };
}
