"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLatestDriftSnapshotPath = getLatestDriftSnapshotPath;
exports.loadLatestDriftSnapshot = loadLatestDriftSnapshot;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const driftSnapshotSchemaVersion = '1.0';
function clampCount(value) {
    if (!Number.isFinite(value) || value < 0) {
        return 0;
    }
    return Math.floor(value);
}
function clampScore(value) {
    if (!Number.isFinite(value)) {
        return 0;
    }
    if (value < 0) {
        return 0;
    }
    if (value > 100) {
        return 100;
    }
    return Math.round(value);
}
function normalizeViolation(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.ruleId !== 'string' || typed.ruleId.trim().length === 0) {
        return undefined;
    }
    if (typeof typed.severity !== 'string' || typed.severity.trim().length === 0) {
        return undefined;
    }
    return {
        ruleId: typed.ruleId.trim(),
        severity: typed.severity.trim(),
        ...(typeof typed.file === 'string' && typed.file.trim().length > 0
            ? { file: typed.file.trim() }
            : {}),
        ...(typeof typed.message === 'string' && typed.message.trim().length > 0
            ? { message: typed.message.trim() }
            : {}),
    };
}
function compareViolation(left, right) {
    const ruleCompare = left.ruleId.localeCompare(right.ruleId);
    if (ruleCompare !== 0) {
        return ruleCompare;
    }
    const fileCompare = (left.file ?? '').localeCompare(right.file ?? '');
    if (fileCompare !== 0) {
        return fileCompare;
    }
    const severityCompare = left.severity.localeCompare(right.severity);
    if (severityCompare !== 0) {
        return severityCompare;
    }
    return (left.message ?? '').localeCompare(right.message ?? '');
}
function normalizeSnapshot(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.generatedAtUtc !== 'string' || typed.generatedAtUtc.trim().length === 0) {
        return undefined;
    }
    const violationsRaw = Array.isArray(typed.violations) ? typed.violations : [];
    const violations = violationsRaw
        .map((entry) => normalizeViolation(entry))
        .filter((entry) => !!entry)
        .sort(compareViolation);
    return {
        schemaVersion: typeof typed.schemaVersion === 'string' && typed.schemaVersion.trim().length > 0
            ? typed.schemaVersion.trim()
            : driftSnapshotSchemaVersion,
        generatedAtUtc: typed.generatedAtUtc,
        score: clampScore(Number(typed.score)),
        errors: clampCount(Number(typed.errors)),
        warnings: clampCount(Number(typed.warnings)),
        info: clampCount(Number(typed.info)),
        passed: clampCount(Number(typed.passed)),
        violations,
    };
}
function getLatestDriftSnapshotPath(workspaceRoot) {
    return path.join(workspaceRoot, '.archpilot', 'history', 'latest-snapshot.json');
}
async function loadLatestDriftSnapshot(workspaceRoot) {
    const snapshotPath = getLatestDriftSnapshotPath(workspaceRoot);
    try {
        const contents = await node_fs_1.promises.readFile(snapshotPath, { encoding: 'utf8' });
        const parsed = JSON.parse(contents);
        return normalizeSnapshot(parsed);
    }
    catch {
        return undefined;
    }
}
//# sourceMappingURL=driftSnapshotLoader.js.map