import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
const LOCAL_BENCHMARKS_DIR = ".nova/local-benchmarks";
function sanitize(value) {
    return value
        .toLowerCase()
        .replace(/[^a-z0-9._-]+/g, "-")
        .replace(/-+/g, "-")
        .replace(/^-|-$/g, "");
}
function nowStamp(date = new Date()) {
    const iso = date.toISOString().replace(/[:]/g, "").replace(/\..+$/, "Z");
    return iso;
}
function resolveBenchDir(cwd) {
    return resolve(cwd, LOCAL_BENCHMARKS_DIR);
}
export function saveBenchmarkReportArtifact(report, options) {
    const cwd = options.cwd ?? process.cwd();
    const dir = resolveBenchDir(cwd);
    if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
    }
    const stamp = nowStamp();
    const backend = sanitize(report.backendHint || "backend");
    const model = sanitize(report.model || "model");
    const tag = options.tag ? `-${sanitize(options.tag)}` : "";
    const id = `${stamp}-${backend}-${model}-${options.mode}${tag}`;
    const path = join(dir, `${id}.json`);
    writeFileSync(path, JSON.stringify(report, null, 2), "utf-8");
    return { id, path, report };
}
export function writeBenchmarkReportToPath(report, path, cwd = process.cwd()) {
    const resolved = resolve(cwd, path);
    const parent = dirname(resolved);
    if (!existsSync(parent)) {
        mkdirSync(parent, { recursive: true });
    }
    writeFileSync(resolved, JSON.stringify(report, null, 2), "utf-8");
    return resolved;
}
function parseArtifactPath(path) {
    try {
        const raw = readFileSync(path, "utf-8");
        const report = JSON.parse(raw);
        const id = basename(path).replace(/\.json$/i, "");
        return { id, path, report };
    }
    catch {
        return undefined;
    }
}
export function listBenchmarkReportArtifacts(cwd = process.cwd()) {
    const dir = resolveBenchDir(cwd);
    if (!existsSync(dir)) {
        return [];
    }
    const files = readdirSync(dir)
        .filter((name) => name.endsWith(".json"))
        .sort()
        .reverse();
    const artifacts = [];
    for (const file of files) {
        const parsed = parseArtifactPath(join(dir, file));
        if (parsed) {
            artifacts.push(parsed);
        }
    }
    return artifacts;
}
export function resolveBenchmarkArtifactRef(ref, cwd = process.cwd()) {
    if (isAbsolute(ref) || ref.includes("/")) {
        return parseArtifactPath(resolve(cwd, ref));
    }
    const artifacts = listBenchmarkReportArtifacts(cwd);
    return artifacts.find((artifact) => artifact.id === ref || artifact.id.startsWith(ref));
}
export function latestBenchmarkSummaryMatrix(cwd = process.cwd()) {
    const artifacts = listBenchmarkReportArtifacts(cwd);
    const latestByKey = new Map();
    for (const artifact of artifacts) {
        const key = `${artifact.report.backendHint}::${artifact.report.model}`;
        if (!latestByKey.has(key)) {
            latestByKey.set(key, artifact);
        }
    }
    return Array.from(latestByKey.entries()).map(([key, artifact]) => ({
        key,
        backendHint: artifact.report.backendHint,
        model: artifact.report.model,
        passRate: artifact.report.passRate,
        executionValidationRate: artifact.report.executionValidationRate,
        averageRepairCount: artifact.report.averageRepairCount,
        artifactId: artifact.id,
    }));
}
//# sourceMappingURL=benchmark-storage.js.map