"use strict";
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAIRunTimeline = buildAIRunTimeline;
exports.buildAIRunQaHealth = buildAIRunQaHealth;
exports.buildAIRunCostPanel = buildAIRunCostPanel;
exports.buildAIRunFalsePassWarnings = buildAIRunFalsePassWarnings;
exports.buildAIRunOperatorView = buildAIRunOperatorView;
var ai_run_evidence_eval_1 = require("./ai-run-evidence-eval");
function cleanText(value, max) {
    if (max === void 0) { max = 1000; }
    return String(value || '').replace(/\s+/g, ' ').trim().slice(0, max);
}
function toIso(value) {
    if (value instanceof Date && Number.isFinite(value.getTime())) {
        return value.toISOString();
    }
    if (value) {
        var parsed = new Date(value);
        if (Number.isFinite(parsed.getTime())) {
            return parsed.toISOString();
        }
    }
    return undefined;
}
function countStatuses(values) {
    var e_1, _a;
    var result = {
        pass: 0,
        fail: 0,
        blocked: 0,
        warn: 0,
        unknown: 0
    };
    try {
        for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
            var value = values_1_1.value;
            var status_1 = cleanText(value.status, 40).toLowerCase();
            if (status_1 === 'pass' || status_1 === 'fail' || status_1 === 'blocked' || status_1 === 'warn') {
                result[status_1] += 1;
            }
            else {
                result.unknown += 1;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return result;
}
function sortTimeline(items) {
    return __spreadArray([], __read(items), false).sort(function (left, right) {
        var leftTime = left.time ? new Date(left.time).getTime() : 0;
        var rightTime = right.time ? new Date(right.time).getTime() : 0;
        return leftTime - rightTime;
    });
}
function buildAIRunTimeline(run) {
    var e_2, _a, e_3, _b, e_4, _c, e_5, _d, e_6, _e;
    var _f, _g, _h, _j;
    var items = [];
    try {
        for (var _k = __values(run.events || []), _l = _k.next(); !_l.done; _l = _k.next()) {
            var event_1 = _l.value;
            items.push({
                time: toIso(event_1.recordedAt),
                type: event_1.type,
                label: event_1.category || event_1.type,
                message: cleanText(event_1.message, 2000),
                evidenceRefs: Array.isArray(event_1.artifactPaths) ? event_1.artifactPaths : [],
                metadata: event_1.metadata
            });
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
        }
        finally { if (e_2) throw e_2.error; }
    }
    try {
        for (var _m = __values(run.gates || []), _o = _m.next(); !_o.done; _o = _m.next()) {
            var gate = _o.value;
            items.push({
                time: toIso(gate.recordedAt),
                type: 'gate',
                label: gate.label || gate.key,
                status: gate.status,
                message: gate.reason,
                evidenceRefs: gate.evidenceRefs || [],
                metadata: gate.metadata
            });
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (_o && !_o.done && (_b = _m.return)) _b.call(_m);
        }
        finally { if (e_3) throw e_3.error; }
    }
    try {
        for (var _p = __values(((_f = run.qa) === null || _f === void 0 ? void 0 : _f.infraChecks) || []), _q = _p.next(); !_q.done; _q = _p.next()) {
            var check = _q.value;
            items.push({
                time: toIso(check.checkedAt),
                type: 'qa_infra',
                label: check.name,
                status: check.status,
                message: check.message,
                evidenceRefs: check.path ? [check.path] : [],
                metadata: check.metadata
            });
        }
    }
    catch (e_4_1) { e_4 = { error: e_4_1 }; }
    finally {
        try {
            if (_q && !_q.done && (_c = _p.return)) _c.call(_p);
        }
        finally { if (e_4) throw e_4.error; }
    }
    if ((_g = run.qa) === null || _g === void 0 ? void 0 : _g.compile) {
        items.push({
            time: toIso(run.qa.compile.recordedAt),
            type: 'qa_compile',
            label: run.qa.compile.command || 'Compile/build',
            status: run.qa.compile.status,
            message: run.qa.compile.message,
            evidenceRefs: run.qa.compile.artifactPath ? [run.qa.compile.artifactPath] : [],
            metadata: run.qa.compile.metadata
        });
    }
    try {
        for (var _r = __values(((_h = run.qa) === null || _h === void 0 ? void 0 : _h.routeProbes) || []), _s = _r.next(); !_s.done; _s = _r.next()) {
            var probe = _s.value;
            items.push({
                time: toIso(probe.recordedAt),
                type: 'qa_route_probe',
                label: probe.route,
                status: probe.status,
                message: probe.message || probe.caption,
                evidenceRefs: probe.screenshot ? [probe.screenshot] : [],
                metadata: probe.metadata
            });
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (_s && !_s.done && (_d = _r.return)) _d.call(_r);
        }
        finally { if (e_5) throw e_5.error; }
    }
    try {
        for (var _t = __values(((_j = run.qa) === null || _j === void 0 ? void 0 : _j.businessAssertions) || []), _u = _t.next(); !_u.done; _u = _t.next()) {
            var assertion = _u.value;
            items.push({
                time: toIso(assertion.recordedAt),
                type: 'qa_business_assertion',
                label: assertion.assertion,
                status: assertion.status,
                message: assertion.observed || assertion.dataProof || assertion.message,
                evidenceRefs: assertion.artifactPaths || [],
                metadata: assertion.metadata
            });
        }
    }
    catch (e_6_1) { e_6 = { error: e_6_1 }; }
    finally {
        try {
            if (_u && !_u.done && (_e = _t.return)) _e.call(_t);
        }
        finally { if (e_6) throw e_6.error; }
    }
    return sortTimeline(items);
}
function buildAIRunQaHealth(run) {
    var _a, _b, _c, _d, _e;
    var infraCounts = countStatuses(((_a = run.qa) === null || _a === void 0 ? void 0 : _a.infraChecks) || []);
    var routeProbes = ((_b = run.qa) === null || _b === void 0 ? void 0 : _b.routeProbes) || [];
    var routePass = routeProbes.filter(function (probe) { return probe.status === 'pass' && probe.shellOnly !== true; }).length;
    var routeFail = routeProbes.filter(function (probe) { return probe.status === 'fail' || probe.status === 'blocked'; }).length;
    var shellOnly = routeProbes.filter(function (probe) { return probe.shellOnly === true; }).length;
    var assertions = ((_c = run.qa) === null || _c === void 0 ? void 0 : _c.businessAssertions) || [];
    var businessPass = assertions.filter(function (assertion) { return assertion.status === 'pass'; }).length;
    var businessFail = assertions.filter(function (assertion) { return assertion.status === 'fail'; }).length;
    var businessBlocked = assertions.filter(function (assertion) { return assertion.status === 'blocked'; }).length;
    return {
        outcome: (_d = run.qa) === null || _d === void 0 ? void 0 : _d.outcome,
        infra: {
            pass: infraCounts.pass,
            fail: infraCounts.fail,
            blocked: infraCounts.blocked,
            warn: infraCounts.warn,
            unknown: infraCounts.unknown
        },
        compile: ((_e = run.qa) === null || _e === void 0 ? void 0 : _e.compile) ? {
            status: run.qa.compile.status,
            stale: run.qa.compile.staleEvidence === true || run.qa.compile.status === 'stale',
            artifactPath: run.qa.compile.artifactPath,
            message: run.qa.compile.message
        } : undefined,
        route: {
            pass: routePass,
            fail: routeFail,
            shellOnly: shellOnly
        },
        business: {
            pass: businessPass,
            fail: businessFail,
            blocked: businessBlocked,
            missing: assertions.length === 0
        }
    };
}
function buildAIRunCostPanel(cost, run) {
    var _a, _b, _c, _d;
    var categories = Object.keys((cost === null || cost === void 0 ? void 0 : cost.categories) || {}).sort().map(function (category) {
        var _a;
        var entry = (_a = cost === null || cost === void 0 ? void 0 : cost.categories) === null || _a === void 0 ? void 0 : _a[category];
        return {
            category: category,
            totalTokens: Number((entry === null || entry === void 0 ? void 0 : entry.totalTokens) || 0),
            estimatedUsd: Number((entry === null || entry === void 0 ? void 0 : entry.estimatedUsd) || 0),
            count: Number((entry === null || entry === void 0 ? void 0 : entry.count) || 0)
        };
    });
    var sources = Object.keys((cost === null || cost === void 0 ? void 0 : cost.sources) || {}).sort().map(function (source) {
        var _a;
        var entry = (_a = cost === null || cost === void 0 ? void 0 : cost.sources) === null || _a === void 0 ? void 0 : _a[source];
        return {
            source: source,
            totalTokens: Number((entry === null || entry === void 0 ? void 0 : entry.totalTokens) || 0),
            estimatedUsd: Number((entry === null || entry === void 0 ? void 0 : entry.estimatedUsd) || 0),
            count: Number((entry === null || entry === void 0 ? void 0 : entry.count) || 0),
            manualCount: Number((entry === null || entry === void 0 ? void 0 : entry.manualCount) || 0),
            untrackedCount: Number((entry === null || entry === void 0 ? void 0 : entry.untrackedCount) || 0)
        };
    });
    var surfaces = Object.keys((cost === null || cost === void 0 ? void 0 : cost.surfaces) || {}).sort().map(function (surface) {
        var _a;
        var entry = (_a = cost === null || cost === void 0 ? void 0 : cost.surfaces) === null || _a === void 0 ? void 0 : _a[surface];
        return {
            surface: surface,
            totalTokens: Number((entry === null || entry === void 0 ? void 0 : entry.totalTokens) || 0),
            estimatedUsd: Number((entry === null || entry === void 0 ? void 0 : entry.estimatedUsd) || 0),
            count: Number((entry === null || entry === void 0 ? void 0 : entry.count) || 0)
        };
    });
    var costGate = (_a = run === null || run === void 0 ? void 0 : run.gates) === null || _a === void 0 ? void 0 : _a.find(function (gate) { return gate.key === 'cost_observability'; });
    var observability = ((_b = run === null || run === void 0 ? void 0 : run.metadata) === null || _b === void 0 ? void 0 : _b.costObservability) || (costGate === null || costGate === void 0 ? void 0 : costGate.metadata) || {};
    return {
        totalTokens: Number((cost === null || cost === void 0 ? void 0 : cost.totalTokens) || 0),
        estimatedUsd: Number((cost === null || cost === void 0 ? void 0 : cost.estimatedUsd) || 0),
        models: Array.isArray(cost === null || cost === void 0 ? void 0 : cost.models) ? cost.models : [],
        categories: categories,
        sources: sources,
        surfaces: surfaces,
        manualEstimatedUsd: Number((cost === null || cost === void 0 ? void 0 : cost.manualEstimatedUsd) || 0),
        untrackedEstimatedUsd: Number((cost === null || cost === void 0 ? void 0 : cost.untrackedEstimatedUsd) || 0),
        untrackedWarnings: Array.isArray(cost === null || cost === void 0 ? void 0 : cost.untrackedWarnings) ? cost.untrackedWarnings : [],
        observabilityStatus: cleanText(observability.status || (costGate === null || costGate === void 0 ? void 0 : costGate.status), 80),
        missingLedger: observability.missingLedger === true || ((_c = costGate === null || costGate === void 0 ? void 0 : costGate.metadata) === null || _c === void 0 ? void 0 : _c.missingLedger) === true,
        externalCodexMonitorUsed: observability.externalCodexMonitorUsed === true || ((_d = costGate === null || costGate === void 0 ? void 0 : costGate.metadata) === null || _d === void 0 ? void 0 : _d.externalCodexMonitorUsed) === true,
        nextAction: cleanText(observability.nextAction, 500)
    };
}
function buildAIRunFalsePassWarnings(run) {
    var _a, _b, _c, _d;
    var warnings = Array.isArray(run.warnings) ? __spreadArray([], __read(run.warnings), false) : [];
    if (run.outcome === 'false_pass' && !warnings.includes('false_pass_outcome')) {
        warnings.push('false_pass_outcome');
    }
    if ((((_a = run.qa) === null || _a === void 0 ? void 0 : _a.outcome) === 'route_only_pass' || ((_b = run.qa) === null || _b === void 0 ? void 0 : _b.outcome) === 'incomplete') && !warnings.includes('missing_business_assertion')) {
        warnings.push('missing_business_assertion');
    }
    if (((_d = (_c = run.qa) === null || _c === void 0 ? void 0 : _c.routeProbes) === null || _d === void 0 ? void 0 : _d.some(function (probe) { return probe.shellOnly === true; })) && !warnings.includes('shell_only_route')) {
        warnings.push('shell_only_route');
    }
    if (run.outcome === 'release_blocked' && !warnings.includes('release_blocked_after_scorecard')) {
        warnings.push('release_blocked_after_scorecard');
    }
    return warnings;
}
function buildAIRunOperatorView(run) {
    return {
        runId: run.id || run._id,
        source: run.source,
        title: run.title,
        outcome: run.outcome,
        failureClass: (0, ai_run_evidence_eval_1.classifyAIRunFailureClass)(run),
        nextAction: run.nextAction,
        warnings: buildAIRunFalsePassWarnings(run),
        timeline: buildAIRunTimeline(run),
        qaHealth: buildAIRunQaHealth(run),
        costPanel: buildAIRunCostPanel(run.cost, run),
        trainingExample: (0, ai_run_evidence_eval_1.buildAIRunTrainingExampleFromRun)(run)
    };
}

//# sourceMappingURL=ai-run-evidence-dashboard.js.map
