"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.getArchitectureDriftTimelineDirectory = getArchitectureDriftTimelineDirectory;
exports.formatArchitectureDriftTimelineFileName = formatArchitectureDriftTimelineFileName;
exports.createArchitectureDriftTimelineSnapshot = createArchitectureDriftTimelineSnapshot;
exports.buildArchitectureDriftTimelineTrendSummary = buildArchitectureDriftTimelineTrendSummary;
exports.normalizeArchitectureDriftTimelineSnapshot = normalizeArchitectureDriftTimelineSnapshot;
exports.writeArchitectureDriftTimelineSnapshot = writeArchitectureDriftTimelineSnapshot;
exports.readArchitectureDriftTimelineSnapshots = readArchitectureDriftTimelineSnapshots;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const node_child_process_1 = require("node:child_process");
const node_util_1 = require("node:util");
const execFile = (0, node_util_1.promisify)(node_child_process_1.execFile);
const timelineFilePattern = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.json$/u;
function clampScore(value) {
    if (!Number.isFinite(value)) {
        return 0;
    }
    if (value < 0) {
        return 0;
    }
    if (value > 100) {
        return 100;
    }
    return Math.round(value);
}
function clampCount(value) {
    if (!Number.isFinite(value) || value < 0) {
        return 0;
    }
    return Math.floor(value);
}
function toRiskLevel(value) {
    const normalized = typeof value === 'string' ? value.trim().toUpperCase() : '';
    return normalized === 'HIGH' || normalized === 'MEDIUM' || normalized === 'LOW'
        ? normalized
        : 'LOW';
}
function toEnforcementOutcome(value) {
    const normalized = typeof value === 'string' ? value.trim().toUpperCase() : '';
    return normalized === 'FAIL' || normalized === 'WARN' || normalized === 'PASS'
        ? normalized
        : 'PASS';
}
function normalizeTimestampUtcIso(timestampUtcIso) {
    const parsed = new Date(timestampUtcIso);
    if (Number.isNaN(parsed.getTime())) {
        return new Date().toISOString();
    }
    return parsed.toISOString();
}
function getArchitectureDriftTimelineDirectory(workspaceRoot) {
    return path.join(workspaceRoot, '.archpilot', 'history');
}
function formatArchitectureDriftTimelineFileName(timestampUtcIso) {
    const normalizedIso = normalizeTimestampUtcIso(timestampUtcIso);
    return `${normalizedIso.slice(0, 19).replace(/:/g, '-')}.json`;
}
function createArchitectureDriftTimelineSnapshot(input) {
    return {
        timestamp: normalizeTimestampUtcIso(input.timestampUtcIso),
        architectureScore: clampScore(input.architectureScore),
        setupReadinessScore: clampScore(input.setupReadinessScore),
        ...(typeof input.moduleCount === 'number'
            ? { moduleCount: clampCount(input.moduleCount) }
            : {}),
        ...(typeof input.edgeCount === 'number' ? { edgeCount: clampCount(input.edgeCount) } : {}),
        errorCount: clampCount(input.errorCount),
        warningCount: clampCount(input.warningCount),
        ...(typeof input.infoCount === 'number' ? { infoCount: clampCount(input.infoCount) } : {}),
        passedCount: clampCount(input.passedCount),
        driftDetected: !!input.driftDetected,
        violationCount: clampCount(input.violationCount),
        changeRiskLevel: toRiskLevel(input.changeRiskLevel),
        governanceRiskLevel: toRiskLevel(input.governanceRiskLevel),
        enforcementOutcome: toEnforcementOutcome(input.enforcementOutcome),
    };
}
function buildArchitectureDriftTimelineTrendSummary(snapshots) {
    if (snapshots.length === 0) {
        return undefined;
    }
    const ordered = [...snapshots].sort((left, right) => left.timestamp.localeCompare(right.timestamp));
    const first = ordered[0].architectureScore;
    const latest = ordered[ordered.length - 1].architectureScore;
    const best = ordered.reduce((max, snapshot) => Math.max(max, snapshot.architectureScore), 0);
    const worst = ordered.reduce((min, snapshot) => Math.min(min, snapshot.architectureScore), 100);
    return {
        latestScore: latest,
        bestScore: best,
        worstScore: worst,
        trend: latest > first ? 'Improving' : latest < first ? 'Declining' : 'Stable',
    };
}
async function tryReadCommitSha(workspaceRoot) {
    try {
        const { stdout } = await execFile('git', ['rev-parse', 'HEAD'], { cwd: workspaceRoot });
        const sha = stdout.trim();
        return sha.length > 0 ? sha : undefined;
    }
    catch {
        return undefined;
    }
}
function normalizeArchitectureDriftTimelineSnapshot(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.timestamp !== 'string' || typed.timestamp.trim().length === 0) {
        return undefined;
    }
    const snapshot = {
        timestamp: normalizeTimestampUtcIso(typed.timestamp),
        architectureScore: clampScore(Number(typed.architectureScore)),
        setupReadinessScore: clampScore(Number(typed.setupReadinessScore)),
        ...(typeof typed.moduleCount === 'number'
            ? { moduleCount: clampCount(Number(typed.moduleCount)) }
            : {}),
        ...(typeof typed.edgeCount === 'number'
            ? { edgeCount: clampCount(Number(typed.edgeCount)) }
            : {}),
        errorCount: clampCount(Number(typed.errorCount)),
        warningCount: clampCount(Number(typed.warningCount)),
        ...(typeof typed.infoCount === 'number'
            ? { infoCount: clampCount(Number(typed.infoCount)) }
            : {}),
        passedCount: clampCount(Number(typed.passedCount)),
        driftDetected: !!typed.driftDetected,
        violationCount: clampCount(Number(typed.violationCount)),
        changeRiskLevel: toRiskLevel(typed.changeRiskLevel),
        governanceRiskLevel: toRiskLevel(typed.governanceRiskLevel),
        enforcementOutcome: toEnforcementOutcome(typed.enforcementOutcome),
    };
    if (typeof typed.commitSha === 'string' && typed.commitSha.trim().length > 0) {
        snapshot.commitSha = typed.commitSha.trim();
    }
    return snapshot;
}
async function writeArchitectureDriftTimelineSnapshot(workspaceRoot, snapshot) {
    const withCommitSha = {
        ...snapshot,
        ...(snapshot.commitSha ? {} : { commitSha: await tryReadCommitSha(workspaceRoot) }),
    };
    const timelineDirectory = getArchitectureDriftTimelineDirectory(workspaceRoot);
    const snapshotPath = path.join(timelineDirectory, formatArchitectureDriftTimelineFileName(withCommitSha.timestamp));
    await node_fs_1.promises.mkdir(timelineDirectory, { recursive: true });
    await node_fs_1.promises.writeFile(snapshotPath, `${JSON.stringify(withCommitSha, null, 2)}\n`, {
        encoding: 'utf8',
    });
    return {
        snapshotPath,
        snapshot: withCommitSha,
    };
}
async function readArchitectureDriftTimelineSnapshots(workspaceRoot) {
    const timelineDirectory = getArchitectureDriftTimelineDirectory(workspaceRoot);
    let entries;
    try {
        entries = await node_fs_1.promises.readdir(timelineDirectory);
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        }
        return [];
    }
    const snapshotFileNames = entries.filter((entry) => timelineFilePattern.test(entry));
    const snapshots = [];
    for (const fileName of snapshotFileNames) {
        try {
            const content = await node_fs_1.promises.readFile(path.join(timelineDirectory, fileName), {
                encoding: 'utf8',
            });
            const parsed = JSON.parse(content);
            const snapshot = normalizeArchitectureDriftTimelineSnapshot(parsed);
            if (snapshot) {
                snapshots.push(snapshot);
            }
        }
        catch {
            // Ignore malformed snapshot files and continue with valid entries.
        }
    }
    return snapshots.sort((left, right) => left.timestamp.localeCompare(right.timestamp));
}
//# sourceMappingURL=architectureDriftTimeline.js.map