"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.getArchitectureHealthHistoryPath = getArchitectureHealthHistoryPath;
exports.createArchitectureHealthSnapshot = createArchitectureHealthSnapshot;
exports.buildArchitectureHealthTrend = buildArchitectureHealthTrend;
exports.buildArchitectureHealthTrendFromSnapshotScores = buildArchitectureHealthTrendFromSnapshotScores;
exports.readArchitectureHealthHistory = readArchitectureHealthHistory;
exports.appendArchitectureHealthSnapshot = appendArchitectureHealthSnapshot;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const historyVersion = 1;
const defaultMaxSnapshots = 100;
function clampScore(score) {
    if (!Number.isFinite(score)) {
        return 0;
    }
    if (score < 0) {
        return 0;
    }
    if (score > 100) {
        return 100;
    }
    return Math.round(score);
}
function clampCount(value) {
    if (!Number.isFinite(value) || value < 0) {
        return 0;
    }
    return Math.floor(value);
}
function normalizeCategoryScores(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return {};
    }
    const normalized = Object.entries(value)
        .filter(([category]) => category.trim().length > 0)
        .map(([category, score]) => [category, clampScore(Number(score))])
        .sort(([left], [right]) => left.localeCompare(right))
        .reduce((accumulator, [category, score]) => {
        accumulator[category] = score;
        return accumulator;
    }, {});
    return normalized;
}
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;
    }
    return {
        generatedAtUtc: typed.generatedAtUtc,
        overallScore: clampScore(Number(typed.overallScore)),
        categoryScores: normalizeCategoryScores(typed.categoryScores),
        totalChecks: clampCount(Number(typed.totalChecks)),
        errors: clampCount(Number(typed.errors)),
        warnings: clampCount(Number(typed.warnings)),
        info: clampCount(Number(typed.info)),
        passed: clampCount(Number(typed.passed)),
    };
}
function normalizeHistory(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return { version: historyVersion, snapshots: [] };
    }
    const typed = value;
    const snapshotsRaw = Array.isArray(typed.snapshots) ? typed.snapshots : [];
    const snapshots = snapshotsRaw
        .map((entry) => normalizeSnapshot(entry))
        .filter((entry) => !!entry)
        .sort((left, right) => left.generatedAtUtc.localeCompare(right.generatedAtUtc));
    return {
        version: historyVersion,
        snapshots,
    };
}
function getArchitectureHealthHistoryPath(workspaceRoot) {
    return path.join(workspaceRoot, '.archpilot', 'history', 'health-history.json');
}
function createArchitectureHealthSnapshot(input) {
    return {
        generatedAtUtc: input.generatedAtUtc,
        overallScore: clampScore(input.overallScore),
        categoryScores: normalizeCategoryScores(input.categoryScores),
        totalChecks: clampCount(input.totalChecks),
        errors: clampCount(input.errors),
        warnings: clampCount(input.warnings),
        info: clampCount(input.info),
        passed: clampCount(input.passed),
    };
}
function buildArchitectureHealthTrend(history) {
    const ordered = [...history.snapshots].sort((left, right) => left.generatedAtUtc.localeCompare(right.generatedAtUtc));
    if (ordered.length === 0) {
        return {
            currentScore: 0,
            trendDirection: 'no-history',
        };
    }
    const current = ordered[ordered.length - 1];
    if (ordered.length === 1) {
        return {
            currentScore: current.overallScore,
            trendDirection: 'no-history',
        };
    }
    const previous = ordered[ordered.length - 2];
    const delta = current.overallScore - previous.overallScore;
    return {
        currentScore: current.overallScore,
        previousScore: previous.overallScore,
        delta,
        trendDirection: delta > 0 ? 'improving' : delta < 0 ? 'declining' : 'stable',
    };
}
function buildArchitectureHealthTrendFromSnapshotScores(currentScore, previousScore) {
    if (previousScore === undefined) {
        return {
            currentScore,
            trendDirection: 'no-history',
        };
    }
    const delta = currentScore - previousScore;
    return {
        currentScore,
        previousScore,
        delta,
        trendDirection: delta > 0 ? 'improving' : delta < 0 ? 'declining' : 'stable',
    };
}
async function readArchitectureHealthHistory(workspaceRoot) {
    const historyPath = getArchitectureHealthHistoryPath(workspaceRoot);
    try {
        const content = await node_fs_1.promises.readFile(historyPath, { encoding: 'utf8' });
        const parsed = JSON.parse(content);
        return { history: normalizeHistory(parsed), recoveredFromInvalidHistory: false };
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return {
                history: { version: historyVersion, snapshots: [] },
                recoveredFromInvalidHistory: false,
            };
        }
        return {
            history: { version: historyVersion, snapshots: [] },
            recoveredFromInvalidHistory: true,
        };
    }
}
async function appendArchitectureHealthSnapshot(workspaceRoot, snapshot, options) {
    const maxSnapshots = options?.maxSnapshots ?? defaultMaxSnapshots;
    const historyPath = getArchitectureHealthHistoryPath(workspaceRoot);
    const loaded = await readArchitectureHealthHistory(workspaceRoot);
    const snapshots = [...loaded.history.snapshots, snapshot]
        .sort((left, right) => left.generatedAtUtc.localeCompare(right.generatedAtUtc))
        .slice(-Math.max(1, maxSnapshots));
    const history = {
        version: historyVersion,
        snapshots,
    };
    await node_fs_1.promises.mkdir(path.dirname(historyPath), { recursive: true });
    await node_fs_1.promises.writeFile(historyPath, `${JSON.stringify(history, null, 2)}\n`, {
        encoding: 'utf8',
    });
    return {
        historyPath,
        history,
        trend: buildArchitectureHealthTrend(history),
        recoveredFromInvalidHistory: loaded.recoveredFromInvalidHistory,
    };
}
//# sourceMappingURL=architectureHealthHistory.js.map