/**
 * Brain Hub client — sync workspace index + fetch account brain context
 * via coder.vigthoria.io (JWT-authenticated).
 */
// Brain Hub calls are an optional personalization enhancement to an agent
// turn, not on the critical path. Native `fetch()` has NO default timeout,
// so a slow/unresponsive coder.vigthoria.io backend previously caused the
// ENTIRE agent turn to hang indefinitely with zero console output, well
// before any "ROUTING DECISION" text is printed (2026-07-10 root-cause).
const BRAIN_HUB_TIMEOUT_MS = 8000;
async function fetchWithTimeout(url, init = {}, timeoutMs = BRAIN_HUB_TIMEOUT_MS) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
        return await fetch(url, { ...init, signal: controller.signal });
    }
    finally {
        clearTimeout(timer);
    }
}
export class BrainHubClient {
    apiBase;
    getAuthToken;
    constructor(options) {
        this.apiBase = (options.apiBase || 'https://coder.vigthoria.io').replace(/\/$/, '');
        this.getAuthToken = options.getAuthToken;
    }
    async headers() {
        const headers = { 'Content-Type': 'application/json' };
        const token = await this.getAuthToken();
        if (token) {
            headers.Authorization = `Bearer ${token}`;
        }
        return headers;
    }
    async syncWorkspaceIndex(payload) {
        const headers = await this.headers();
        if (!headers.Authorization) {
            return { ok: false, skipped: true, reason: 'not_authenticated' };
        }
        try {
            const resp = await fetchWithTimeout(`${this.apiBase}/api/brain/sync-index`, {
                method: 'POST',
                headers,
                body: JSON.stringify(payload),
            });
            const data = await resp.json().catch(() => ({}));
            if (!resp.ok) {
                return { ok: false, error: data.error || `HTTP ${resp.status}` };
            }
            return data;
        }
        catch (error) {
            const timedOut = error instanceof Error && error.name === 'AbortError';
            return { ok: false, error: timedOut ? `timeout after ${BRAIN_HUB_TIMEOUT_MS}ms` : String(error) };
        }
    }
    async fetchAccountContext(limit = 25) {
        const headers = await this.headers();
        if (!headers.Authorization) {
            return { ok: false, formattedText: '', memories: [] };
        }
        try {
            const resp = await fetchWithTimeout(`${this.apiBase}/api/brain/context?limit=${limit}`, { headers });
            const data = await resp.json().catch(() => ({}));
            if (!resp.ok) {
                return { ok: false, formattedText: '', error: data.error || `HTTP ${resp.status}` };
            }
            return data;
        }
        catch (error) {
            const timedOut = error instanceof Error && error.name === 'AbortError';
            return { ok: false, formattedText: '', error: timedOut ? `timeout after ${BRAIN_HUB_TIMEOUT_MS}ms` : String(error) };
        }
    }
}
