import { useCallback, useEffect, useRef, useState } from "react";
function useDiscoveryModels(ctx) {
    const [models, setModels] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const abortRef = useRef(null);
    const fetchModels = useCallback(async ()=>{
        if (!ctx) return;
        abortRef.current?.abort();
        const ctrl = new AbortController();
        abortRef.current = ctrl;
        setLoading(true);
        setError(null);
        const base = (ctx.baseUrl ?? '').replace(/\/$/, '');
        const params = new URLSearchParams();
        if (false === ctx.onlyAvailableModels) params.set('onlyAvailableModels', 'false');
        const qs = params.toString();
        const url = `${base}/api/discovery${qs ? `?${qs}` : ''}`;
        const headers = {
            Authorization: `Bearer ${ctx.token}`,
            Accept: 'application/json',
            'X-UiPath-Internal-AccountId': ctx.accountId,
            'X-UiPath-Internal-TenantId': ctx.tenantId,
            'X-UiPath-LlmGateway-RequestingProduct': ctx.requestingProduct,
            'X-UiPath-LlmGateway-RequestingFeature': ctx.requestingFeature
        };
        if (ctx.operationCode) headers['X-UiPath-LlmGateway-OperationCode'] = ctx.operationCode;
        if (ctx.folderKey) headers['X-UiPath-FolderKey'] = ctx.folderKey;
        if (ctx.fromDedicatedCloud) headers['X-UiPath-LlmGateway-FromDedicatedCloud'] = 'true';
        try {
            const res = await fetch(url, {
                headers,
                signal: ctrl.signal
            });
            if (!res.ok) throw new Error(`Discovery API ${res.status} ${res.statusText}`);
            const data = await res.json();
            const list = Array.isArray(data) ? data : data.models ?? [];
            if (!ctrl.signal.aborted) setModels(normalizeKeys(list));
        } catch (err) {
            if (err?.name === 'AbortError') return;
            if (!ctrl.signal.aborted) setError(err instanceof Error ? err : new Error(String(err)));
        } finally{
            if (!ctrl.signal.aborted) setLoading(false);
        }
    }, [
        ctx
    ]);
    useEffect(()=>{
        if (!ctx) {
            abortRef.current?.abort();
            setModels([]);
            setLoading(false);
            setError(null);
            return;
        }
        fetchModels();
        return ()=>abortRef.current?.abort();
    }, [
        ctx,
        fetchModels
    ]);
    return {
        models,
        loading,
        error,
        refetch: fetchModels
    };
}
function camelizeDeep(value) {
    if (Array.isArray(value)) return value.map(camelizeDeep);
    if (!value || 'object' != typeof value) return value;
    const camel = Object.create(null);
    for (const [k, v] of Object.entries(value))camel[k.charAt(0).toLowerCase() + k.slice(1)] = camelizeDeep(v);
    return camel;
}
function normalizeKeys(list) {
    return list.map((raw)=>camelizeDeep(raw));
}
export { useDiscoveryModels };
