"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
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.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIRunEvidenceManager = void 0;
exports.resolveAIRunStableId = resolveAIRunStableId;
exports.normalizeAIRunForPersistence = normalizeAIRunForPersistence;
var crypto_1 = require("crypto");
var ai_run_collection_1 = require("../collections/ai-run.collection");
var common_1 = require("../util/common");
var ai_run_evidence_eval_1 = require("../util/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 safeKey(value) {
    var cleaned = cleanText(value, 300).toLowerCase().replace(/[^a-z0-9_.:-]+/g, '-').replace(/^-+|-+$/g, '');
    return cleaned || (0, crypto_1.createHash)('sha1').update(value || (0, common_1.objectIdHexString)()).digest('hex').slice(0, 24);
}
function normalizeDate(value) {
    if (value instanceof Date && Number.isFinite(value.getTime())) {
        return value;
    }
    if (value) {
        var parsed = new Date(value);
        if (Number.isFinite(parsed.getTime())) {
            return parsed;
        }
    }
    return undefined;
}
function countBy(values) {
    var e_1, _a;
    var result = {};
    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;
            result[value] = (result[value] || 0) + 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 stripUndefined(value) {
    var e_2, _a;
    var next = {};
    try {
        for (var _b = __values(Object.keys(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
            var key = _c.value;
            if (value[key] !== undefined) {
                next[key] = value[key];
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return next;
}
function resolveSourceKey(run) {
    var e_3, _a, e_4, _b;
    var sourceIds = run.sourceIds || {};
    var priorityKeys = [
        'ticketNumber',
        'ticketId',
        'appId',
        'jobId',
        'conversationId',
        'domain',
        'userId'
    ];
    try {
        for (var priorityKeys_1 = __values(priorityKeys), priorityKeys_1_1 = priorityKeys_1.next(); !priorityKeys_1_1.done; priorityKeys_1_1 = priorityKeys_1.next()) {
            var key = priorityKeys_1_1.value;
            if (sourceIds[key]) {
                return "".concat(key, ":").concat(sourceIds[key]);
            }
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (priorityKeys_1_1 && !priorityKeys_1_1.done && (_a = priorityKeys_1.return)) _a.call(priorityKeys_1);
        }
        finally { if (e_3) throw e_3.error; }
    }
    var sortedSourceIds = {};
    try {
        for (var _c = __values(Object.keys(sourceIds).sort()), _d = _c.next(); !_d.done; _d = _c.next()) {
            var key = _d.value;
            var value = cleanText(sourceIds[key], 300);
            if (value) {
                sortedSourceIds[key] = value;
            }
        }
    }
    catch (e_4_1) { e_4 = { error: e_4_1 }; }
    finally {
        try {
            if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
        }
        finally { if (e_4) throw e_4.error; }
    }
    if (Object.keys(sortedSourceIds).length) {
        return JSON.stringify(sortedSourceIds);
    }
    return [
        run.title || '',
        run.status || '',
        run.phase || '',
        run.startedAt || '',
        run.completedAt || ''
    ].join('|');
}
function resolveAIRunStableId(run) {
    if (run.id) {
        return cleanText(run.id, 240);
    }
    var source = cleanText(run.source, 80) || 'unknown';
    var sourceKey = resolveSourceKey(run);
    var compactSourceKey = safeKey(sourceKey);
    if (compactSourceKey.length <= 160) {
        return "ai-run:".concat(source, ":").concat(compactSourceKey);
    }
    var digest = (0, crypto_1.createHash)('sha1').update("".concat(source, ":").concat(sourceKey)).digest('hex').slice(0, 32);
    return "ai-run:".concat(source, ":").concat(digest);
}
function normalizeAIRunForPersistence(run) {
    var _id = resolveAIRunStableId(run);
    return stripUndefined({
        _id: _id,
        source: run.source || 'unknown',
        sourceIds: run.sourceIds || {},
        title: cleanText(run.title, 500),
        status: cleanText(run.status, 160),
        phase: cleanText(run.phase, 160),
        startedAt: normalizeDate(run.startedAt),
        completedAt: normalizeDate(run.completedAt),
        outcome: run.outcome || 'unknown',
        events: Array.isArray(run.events) ? run.events : [],
        gates: Array.isArray(run.gates) ? run.gates : [],
        qa: run.qa,
        cost: run.cost,
        nextAction: cleanText(run.nextAction, 2000),
        warnings: Array.isArray(run.warnings) ? run.warnings.map(function (warning) { return cleanText(warning, 300); }).filter(Boolean) : [],
        metadata: __assign(__assign({}, (run.metadata || {})), { failureClass: (0, ai_run_evidence_eval_1.classifyAIRunFailureClass)(run), sourceRunId: run.id || '' })
    });
}
function buildAIRunFindQuery(query) {
    var e_5, _a;
    var _b;
    if (query === void 0) { query = {}; }
    var selector = {};
    if (query.source) {
        selector.source = query.source;
    }
    if (query.outcome) {
        selector.outcome = query.outcome;
    }
    try {
        for (var _c = __values(Object.keys(query.sourceIds || {})), _d = _c.next(); !_d.done; _d = _c.next()) {
            var key = _d.value;
            var value = cleanText((_b = query.sourceIds) === null || _b === void 0 ? void 0 : _b[key], 300);
            if (value) {
                selector["sourceIds.".concat(key)] = value;
            }
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
        }
        finally { if (e_5) throw e_5.error; }
    }
    var updatedAt = {};
    var updatedAfter = normalizeDate(query.updatedAfter);
    var updatedBefore = normalizeDate(query.updatedBefore);
    if (updatedAfter) {
        updatedAt.$gte = updatedAfter;
    }
    if (updatedBefore) {
        updatedAt.$lte = updatedBefore;
    }
    if (Object.keys(updatedAt).length) {
        selector.updatedAt = updatedAt;
    }
    return selector;
}
var AIRunEvidenceManager = /** @class */ (function () {
    function AIRunEvidenceManager() {
    }
    AIRunEvidenceManager.upsertRuns = function (runs) {
        return __awaiter(this, void 0, void 0, function () {
            var docs, operations, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        docs = runs.map(function (run) { return normalizeAIRunForPersistence(run); });
                        operations = docs.map(function (doc) {
                            var _id = doc._id, createdAt = doc.createdAt, setDoc = __rest(doc, ["_id", "createdAt"]);
                            return {
                                updateOne: {
                                    filter: { _id: _id },
                                    update: {
                                        $set: __assign(__assign({}, setDoc), { updatedAt: new Date() }),
                                        $setOnInsert: {
                                            _id: _id,
                                            createdAt: createdAt || new Date()
                                        }
                                    },
                                    upsert: true
                                }
                            };
                        });
                        if (!operations.length) {
                            return [2 /*return*/, {
                                    requested: 0,
                                    upsertedCount: 0,
                                    matchedCount: 0,
                                    modifiedCount: 0,
                                    ids: []
                                }];
                        }
                        return [4 /*yield*/, ai_run_collection_1.AIRuns.bulkWrite(operations, { ordered: false }, false, true, true)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, {
                                requested: docs.length,
                                upsertedCount: Number((result === null || result === void 0 ? void 0 : result.upsertedCount) || 0),
                                matchedCount: Number((result === null || result === void 0 ? void 0 : result.matchedCount) || 0),
                                modifiedCount: Number((result === null || result === void 0 ? void 0 : result.modifiedCount) || 0),
                                ids: docs.map(function (doc) { return String(doc._id || ''); }).filter(Boolean)
                            }];
                }
            });
        });
    };
    AIRunEvidenceManager.findRuns = function () {
        return __awaiter(this, arguments, void 0, function (query) {
            var limit, skip;
            if (query === void 0) { query = {}; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        limit = Math.min(Math.max(Number(query.limit || 100), 1), 1000);
                        skip = Math.max(Number(query.skip || 0), 0);
                        return [4 /*yield*/, ai_run_collection_1.AIRuns.find(buildAIRunFindQuery(query), {
                                sort: { updatedAt: -1 },
                                limit: limit,
                                skip: skip
                            })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AIRunEvidenceManager.summarizeRuns = function () {
        return __awaiter(this, arguments, void 0, function (query) {
            var runs, estimatedUsd, totalTokens;
            if (query === void 0) { query = {}; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.findRuns(__assign(__assign({}, query), { limit: Math.min(Math.max(Number(query.limit || 1000), 1), 5000) }))];
                    case 1:
                        runs = _a.sent();
                        estimatedUsd = runs.reduce(function (sum, run) { var _a; return sum + (Number((_a = run.cost) === null || _a === void 0 ? void 0 : _a.estimatedUsd) || 0); }, 0);
                        totalTokens = runs.reduce(function (sum, run) { var _a; return sum + (Number((_a = run.cost) === null || _a === void 0 ? void 0 : _a.totalTokens) || 0); }, 0);
                        return [2 /*return*/, {
                                total: runs.length,
                                bySource: countBy(runs.map(function (run) { return run.source || 'unknown'; })),
                                byOutcome: countBy(runs.map(function (run) { return run.outcome || 'unknown'; })),
                                byFailureClass: countBy(runs.map(function (run) { var _a; return String(((_a = run.metadata) === null || _a === void 0 ? void 0 : _a.failureClass) || 'unknown'); })),
                                estimatedUsd: Number(estimatedUsd.toFixed(6)),
                                totalTokens: totalTokens
                            }];
                }
            });
        });
    };
    AIRunEvidenceManager.exportRuns = function () {
        return __awaiter(this, arguments, void 0, function (query, options) {
            var runs;
            if (query === void 0) { query = {}; }
            if (options === void 0) { options = {}; }
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.findRuns(__assign(__assign({}, query), { limit: Math.min(Math.max(Number(query.limit || 1000), 1), 5000) }))];
                    case 1:
                        runs = _a.sent();
                        return [2 /*return*/, (0, ai_run_evidence_eval_1.buildAIRunDatasetExport)(runs, options)];
                }
            });
        });
    };
    return AIRunEvidenceManager;
}());
exports.AIRunEvidenceManager = AIRunEvidenceManager;

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