// Planu — Registry Auto-Updater
// Updates docs-registry.json with data from web.
// Respects userAdded entries — they are never overwritten.
import { readFile, writeFile } from 'node:fs/promises';
// === Public API ===
export async function loadRegistry(registryPath) {
    try {
        const content = await readFile(registryPath, 'utf-8');
        return JSON.parse(content);
    }
    catch {
        return { frameworks: {}, languages: {}, services: {} };
    }
}
export async function saveRegistry(registryPath, registry) {
    const content = JSON.stringify(registry, null, 2) + '\n';
    await writeFile(registryPath, content, 'utf-8');
}
export function updateDocsRegistryEntry(registry, category, key, entry) {
    const existing = registry[category][key];
    // Never overwrite user-added entries
    if (existing?.userAdded) {
        return registry;
    }
    return {
        ...registry,
        [category]: {
            ...registry[category],
            [key]: {
                ...entry,
                lastFetched: new Date().toISOString(),
            },
        },
    };
}
export async function searchAndRegisterFramework(name, registry) {
    const normalized = name.toLowerCase().replace(/\s+/g, '-');
    // Check if already registered
    if (registry.frameworks[normalized] ??
        registry.languages[normalized] ??
        registry.services[normalized]) {
        return { registry, found: true };
    }
    // Try to discover docs URL via common patterns
    const docsUrl = await discoverDocsUrl(normalized);
    if (!docsUrl) {
        return { registry, found: false };
    }
    const entry = {
        base: docsUrl,
        search: `${docsUrl}?q={topic}`,
        lastFetched: new Date().toISOString(),
    };
    const updated = updateDocsRegistryEntry(registry, 'frameworks', normalized, entry);
    return { registry: updated, found: true };
}
export function getRegistryHealth(registry) {
    const oneHourAgo = Date.now() - 3_600_000;
    let total = 0;
    let fresh = 0;
    let stale = 0;
    let lastUpdated = '';
    for (const category of ['frameworks', 'languages', 'services']) {
        for (const entry of Object.values(registry[category])) {
            total++;
            if (entry.lastFetched) {
                const fetchedAt = new Date(entry.lastFetched).getTime();
                if (fetchedAt > oneHourAgo) {
                    fresh++;
                }
                else {
                    stale++;
                }
                if (entry.lastFetched > lastUpdated) {
                    lastUpdated = entry.lastFetched;
                }
            }
            else {
                stale++;
            }
        }
    }
    return {
        registryFile: 'docs-registry.json',
        entriesTotal: total,
        entriesFresh: fresh,
        entriesStale: stale,
        lastUpdated: lastUpdated || new Date().toISOString(),
    };
}
export function mergeRegistryData(local, remote) {
    const merged = {
        frameworks: { ...local.frameworks },
        languages: { ...local.languages },
        services: { ...local.services },
    };
    for (const category of ['frameworks', 'languages', 'services']) {
        for (const [key, entry] of Object.entries(remote[category])) {
            const existing = merged[category][key];
            // Never overwrite user-added entries
            if (existing?.userAdded) {
                continue;
            }
            merged[category][key] = { ...entry, lastFetched: new Date().toISOString() };
        }
    }
    return merged;
}
// === Internal ===
const TIMEOUT_MS = 8_000;
async function discoverDocsUrl(name) {
    // Common docs URL patterns
    const candidates = [
        `https://${name}.dev/docs`,
        `https://${name}.io/docs`,
        `https://docs.${name}.com`,
        `https://${name}.org/docs`,
        `https://www.${name}.com/docs`,
    ];
    for (const url of candidates) {
        try {
            const response = await globalThis.fetch(url, {
                method: 'HEAD',
                signal: AbortSignal.timeout(TIMEOUT_MS),
                redirect: 'follow',
            });
            if (response.ok) {
                return url;
            }
        }
        catch {
            // Try next candidate
        }
    }
    return null;
}
//# sourceMappingURL=registry-updater.js.map