// Planu — Migration catalog loader (SPEC-054)
// Reads migration-policies-catalog.json and merges custom policies.
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
/** Load catalog from bundled JSON config. */
export function loadBuiltinCatalog() {
    return require('../../config/migration-policies-catalog.json');
}
/** Optionally load a custom catalog override from projectPath/.planu/migration-policies.json. */
export async function loadCustomCatalog(projectPath) {
    const customPath = `${projectPath}/.planu/migration-policies.json`;
    try {
        const content = await readFile(customPath, 'utf-8');
        const parsed = JSON.parse(content);
        if (parsed !== null &&
            typeof parsed === 'object' &&
            'customPolicies' in parsed &&
            Array.isArray(parsed.customPolicies)) {
            return parsed.customPolicies;
        }
        return [];
    }
    catch {
        return [];
    }
}
/** Merge custom policies into the built-in catalog, overriding matching entries. */
export function mergeCatalogPolicies(catalog, customPolicies) {
    if (customPolicies.length === 0) {
        return catalog;
    }
    const merged = {
        ...catalog,
        ecosystems: { ...catalog.ecosystems },
        customPolicies: [...catalog.customPolicies, ...customPolicies],
    };
    for (const policy of customPolicies) {
        const eco = policy.ecosystem;
        const existing = merged.ecosystems[eco];
        const entry = existing
            ? { ...existing, knownMajors: { ...existing.knownMajors } }
            : { knownMajors: {} };
        entry.knownMajors[policy.package] = policy.latestMajor;
        if (policy.eolDate) {
            const eolList = entry.eolPackages ? [...entry.eolPackages] : [];
            eolList.push({
                name: policy.package,
                major: policy.latestMajor - 1,
                eolDate: policy.eolDate,
            });
            entry.eolPackages = eolList;
        }
        if (policy.securityRisk === true) {
            const secList = entry.securityRiskPackages ? [...entry.securityRiskPackages] : [];
            secList.push(policy.package);
            entry.securityRiskPackages = secList;
        }
        merged.ecosystems[eco] = entry;
    }
    return merged;
}
/** Get the latest known major for a package in a given ecosystem. Returns null if unknown. */
export function getLatestKnownMajor(catalog, ecosystem, pkg) {
    const ecoEntry = catalog.ecosystems[ecosystem];
    if (!ecoEntry) {
        return null;
    }
    const known = ecoEntry.knownMajors[pkg];
    return known ?? null;
}
//# sourceMappingURL=catalog-loader.js.map