import AjvImport from "ajv";
import { existsSync, readFileSync } from "node:fs";
import { unwrapKitJsonExportPayload } from "../../core/kit-export-envelope.js";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const moduleDir = dirname(fileURLToPath(import.meta.url));
function resolvePackagedSchemaPath(schemaFile) {
    const nextToDist = join(moduleDir, "schemas", schemaFile);
    if (existsSync(nextToDist)) {
        return nextToDist;
    }
    const fromDistTree = join(moduleDir, "..", "..", "..", "src", "modules", "documentation", "schemas", schemaFile);
    if (existsSync(fromDistTree)) {
        return fromDistTree;
    }
    return nextToDist;
}
function loadSchema(name) {
    const p = resolvePackagedSchemaPath(name);
    return JSON.parse(readFileSync(p, "utf8"));
}
function formatAjvErrors(errors, dataPath = "") {
    if (!errors?.length) {
        return dataPath ? [`${dataPath}: validation failed`] : ["validation failed"];
    }
    return errors.map((e) => {
        const p = e.instancePath?.length ? e.instancePath : "(root)";
        return `${p}: ${e.message ?? e.keyword ?? "error"}`;
    });
}
let roadmapValidate = null;
let taxonomyValidate = null;
function createAjv() {
    const Ctor = AjvImport;
    return new Ctor({ allErrors: true, strict: false });
}
function getRoadmapValidate() {
    if (!roadmapValidate) {
        const compiled = createAjv().compile(loadSchema("roadmap-data.schema.json"));
        if (!compiled) {
            throw new Error("Failed to compile roadmap-data.schema.json");
        }
        roadmapValidate = compiled;
    }
    return roadmapValidate;
}
function getTaxonomyValidate() {
    if (!taxonomyValidate) {
        const compiled = createAjv().compile(loadSchema("feature-taxonomy.schema.json"));
        if (!compiled) {
            throw new Error("Failed to compile feature-taxonomy.schema.json");
        }
        taxonomyValidate = compiled;
    }
    return taxonomyValidate;
}
export function validateRoadmapData(input) {
    const v = getRoadmapValidate();
    if (!v(input)) {
        return { ok: false, errors: formatAjvErrors(v.errors) };
    }
    return { ok: true, data: input };
}
export function validateFeatureTaxonomyData(input) {
    const v = getTaxonomyValidate();
    if (!v(input)) {
        return { ok: false, errors: formatAjvErrors(v.errors) };
    }
    const data = input;
    const seen = new Set();
    const dups = [];
    for (const f of data.features) {
        if (seen.has(f.slug)) {
            dups.push(f.slug);
        }
        seen.add(f.slug);
    }
    if (dups.length > 0) {
        return { ok: false, errors: [`duplicate taxonomy slug(s): ${[...new Set(dups)].join(", ")}`] };
    }
    return { ok: true, data };
}
export function documentationDataDir(sourceRoot) {
    return join(sourceRoot, "src", "modules", "documentation", "data");
}
export function readAndValidateRoadmapData(sourceRoot) {
    const dir = documentationDataDir(sourceRoot);
    const path = join(dir, "roadmap-data.json");
    let parsed;
    try {
        parsed = JSON.parse(readFileSync(path, "utf8"));
    }
    catch (e) {
        return { ok: false, errors: [`${path}: ${e.message}`], path };
    }
    const v = validateRoadmapData(parsed);
    if (!v.ok) {
        return { ok: false, errors: v.errors.map((err) => `${path}: ${err}`), path };
    }
    return { ok: true, data: v.data, path };
}
export function readAndValidateFeatureTaxonomyData(sourceRoot, taxonomyFileName) {
    const dir = documentationDataDir(sourceRoot);
    const path = join(dir, taxonomyFileName);
    let parsed;
    try {
        parsed = unwrapKitJsonExportPayload(JSON.parse(readFileSync(path, "utf8")));
    }
    catch (e) {
        return { ok: false, errors: [`${path}: ${e.message}`], path };
    }
    const v = validateFeatureTaxonomyData(parsed);
    if (!v.ok) {
        return { ok: false, errors: v.errors.map((err) => `${path}: ${err}`), path };
    }
    return { ok: true, data: v.data, path };
}
