import { resolveEngine, buildApiUrl, logError, logInfo } from '../utils';

/**
 * Discover the model list exposed by the local AI engine at `baseUrl`.
 *
 * Same wire format as the sidebar's `_sendModels` (which still owns the
 * sidebar-specific caching/UI logic) — extracted here so the settings panel
 * can fetch the same list without depending on the sidebar provider.
 *
 * Returns an empty array on any failure (offline engine, parse error, etc.).
 * Callers should treat the result as a hint, not a hard list.
 */
export async function discoverModels(baseUrl: string, timeoutMs: number = 5000): Promise<string[]> {
    const url = (baseUrl || '').trim();
    if (!url) return [];
    const engine = resolveEngine(url);
    const modelsUrl = buildApiUrl(url, engine, 'models');
    try {
        const res = await fetch(modelsUrl, { signal: AbortSignal.timeout(timeoutMs) });
        if (!res.ok) {
            logInfo('discoverModels: non-OK status', { engine, modelsUrl, status: res.status });
            return [];
        }
        const text = await res.text();
        if (!text) return [];
        const data = JSON.parse(text) as any;
        const list: string[] = engine === 'lmstudio'
            ? (data.data || []).map((m: any) => m.id)
            : (data.models || []).map((m: any) => m.name);
        return list.filter((m): m is string => typeof m === 'string' && m.length > 0);
    } catch (e: any) {
        logError('discoverModels failed.', { engine, modelsUrl, error: e?.message ?? String(e) });
        return [];
    }
}
