import { readJson, writeJson, projectDataDir } from './base-store.js';
import { withFileLock } from './file-mutex.js';
function baselineFile(projectId) {
    return `${projectDataDir(projectId)}/convention-baseline.json`;
}
/**
 * Persist a convention baseline for a project.
 * Overwrites any previously stored baseline.
 */
export async function saveBaseline(projectId, baseline) {
    await withFileLock(baselineFile(projectId), async () => {
        await writeJson(baselineFile(projectId), baseline);
    });
}
/**
 * Retrieve the stored baseline for a project.
 * Returns null when no baseline has been established yet.
 */
export async function getBaseline(projectId) {
    return readJson(baselineFile(projectId), null);
}
/**
 * Build a stable key for a violation used to detect equivalence between scans.
 * Two violations with the same key are considered the same issue.
 */
function violationKey(v) {
    return `${v.ruleId}::${v.file}::${v.line ?? 0}`;
}
/**
 * Compare a current scan result against the stored baseline.
 * Returns new violations (regressions) and fixed violations (improvements).
 * If no baseline exists, all current violations are treated as new.
 */
export async function compareWithBaseline(projectId, current) {
    const baseline = await getBaseline(projectId);
    if (!baseline) {
        return {
            newViolations: current.violations,
            fixedViolations: [],
            totalDelta: current.violations.length,
            regressionDetected: current.violations.length > 0,
        };
    }
    const baselineKeys = new Set(baseline.snapshot.violations.map(violationKey));
    const currentKeys = new Set(current.violations.map(violationKey));
    const newViolations = current.violations.filter((v) => !baselineKeys.has(violationKey(v)));
    const fixedViolations = baseline.snapshot.violations.filter((v) => !currentKeys.has(violationKey(v)));
    const totalDelta = newViolations.length - fixedViolations.length;
    return {
        newViolations,
        fixedViolations,
        totalDelta,
        regressionDetected: totalDelta > 0,
    };
}
export { baselineFile };
//# sourceMappingURL=convention-baseline.js.map