import { get } from "./serviceHelper";
let manualTocCache = null;
let manualTocInFlight = null;
const MANUAL_TOC_TTL_MS = 60_000; // 1 minute
const MANUAL_LOAD_RETRY_DELAYS_MS = [250, 750];
async function withManualLoadRetry(operation) {
    let lastError;
    for (let attempt = 0; attempt <= MANUAL_LOAD_RETRY_DELAYS_MS.length; attempt += 1) {
        try {
            return await operation();
        }
        catch (error) {
            lastError = error;
            const delay = MANUAL_LOAD_RETRY_DELAYS_MS[attempt];
            if (delay === undefined) {
                break;
            }
            await new Promise((resolve) => setTimeout(resolve, delay));
        }
    }
    throw lastError;
}
export async function loadManualToc() {
    const url = "/parhelia/manual/toc";
    // Serve from cache if fresh
    if (manualTocCache &&
        Date.now() - manualTocCache.timestamp < MANUAL_TOC_TTL_MS) {
        return manualTocCache.data;
    }
    // Reuse in-flight request
    if (manualTocInFlight)
        return manualTocInFlight;
    manualTocInFlight = withManualLoadRetry(async () => {
        const response = await get(url);
        if (response.type !== "success") {
            throw new Error("Error loading manual table of contents");
        }
        const data = response.data || [];
        manualTocCache = { timestamp: Date.now(), data };
        return data;
    }).finally(() => {
        manualTocInFlight = null;
    });
    return manualTocInFlight;
}
const manualSectionCache = new Map();
const MANUAL_SECTION_TTL_MS = 60_000; // 1 minute
/**
 * Invalidate the cache for a specific manual section (or all sections if id is not provided)
 * Call this when you know a section has been updated via websocket
 */
export function invalidateManualSectionCache(id) {
    if (id) {
        manualSectionCache.delete(id);
    }
    else {
        manualSectionCache.clear();
    }
}
export async function loadManualSection(id) {
    const url = `/parhelia/manual/${id}`;
    // Serve from cache if fresh
    const cached = manualSectionCache.get(id);
    if (cached && Date.now() - cached.timestamp < MANUAL_SECTION_TTL_MS) {
        return cached.data;
    }
    const response = await get(url);
    if (response.type !== "success") {
        return null;
    }
    const data = response.data;
    if (data) {
        manualSectionCache.set(id, { timestamp: Date.now(), data });
    }
    return data || null;
}
//# sourceMappingURL=manualService.js.map