"use strict";
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 __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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadDiagnosticMethods = loadDiagnosticMethods;
var simpl_schema_1 = require("simpl-schema");
var user_collection_1 = require("../collections/user.collection");
var resolveio_server_app_1 = require("../resolveio-server-app");
var MAX_LIST_LIMIT = 250;
var DEFAULT_LIST_LIMIT = 50;
function normalizeString(value, maxLength) {
    if (maxLength === void 0) { maxLength = 500; }
    var normalized = String(value || '').trim();
    if (!normalized) {
        return '';
    }
    if (normalized.length <= maxLength) {
        return normalized;
    }
    return normalized.slice(0, maxLength);
}
function normalizeBoolean(value) {
    if (typeof value === 'boolean') {
        return value;
    }
    if (typeof value === 'string') {
        var normalized = value.trim().toLowerCase();
        if (['true', '1', 'yes', 'y'].includes(normalized)) {
            return true;
        }
        if (['false', '0', 'no', 'n'].includes(normalized)) {
            return false;
        }
    }
    return undefined;
}
function normalizeLimit(value) {
    var parsed = Number(value);
    if (!Number.isFinite(parsed) || parsed <= 0) {
        return DEFAULT_LIST_LIMIT;
    }
    return Math.min(Math.floor(parsed), MAX_LIST_LIMIT);
}
function normalizeSkip(value) {
    var parsed = Number(value);
    if (!Number.isFinite(parsed) || parsed < 0) {
        return 0;
    }
    return Math.floor(parsed);
}
function normalizeSortDirection(value) {
    var normalized = normalizeString(value, 10).toLowerCase();
    return normalized === 'asc' ? 1 : -1;
}
function escapeRegex(value) {
    return String(value || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function assertSuperAdmin(context) {
    return __awaiter(this, void 0, void 0, function () {
        var idUser, user;
        var _a, _b, _c, _d, _e;
        return __generator(this, function (_f) {
            switch (_f.label) {
                case 0:
                    if ((context === null || context === void 0 ? void 0 : context.user) === 'Internal System') {
                        return [2 /*return*/];
                    }
                    if ((_b = (_a = context === null || context === void 0 ? void 0 : context.user) === null || _a === void 0 ? void 0 : _a.roles) === null || _b === void 0 ? void 0 : _b.super_admin) {
                        return [2 /*return*/];
                    }
                    idUser = normalizeString((context === null || context === void 0 ? void 0 : context.id_user)
                        || (context === null || context === void 0 ? void 0 : context.idUser)
                        || ((_c = context === null || context === void 0 ? void 0 : context.user) === null || _c === void 0 ? void 0 : _c._id)
                        || ((_d = context === null || context === void 0 ? void 0 : context.user) === null || _d === void 0 ? void 0 : _d.id_user));
                    if (!idUser) {
                        throw new Error('Only super admins can access diagnostics.');
                    }
                    return [4 /*yield*/, user_collection_1.Users.findById(idUser, {
                            projection: {
                                _id: 1,
                                roles: 1
                            }
                        })];
                case 1:
                    user = _f.sent();
                    if (!((_e = user === null || user === void 0 ? void 0 : user.roles) === null || _e === void 0 ? void 0 : _e.super_admin)) {
                        throw new Error('Only super admins can access diagnostics.');
                    }
                    return [2 /*return*/];
            }
        });
    });
}
function resolveSortField(value, allowedFields, fallback) {
    var normalized = normalizeString(value, 80);
    if (!normalized) {
        return fallback;
    }
    if (allowedFields.includes(normalized)) {
        return normalized;
    }
    return fallback;
}
function buildAutoFixSearchQuery(payload) {
    var query = {};
    var andClauses = [];
    var status = normalizeString(payload === null || payload === void 0 ? void 0 : payload.status, 40).toLowerCase();
    var sourceType = normalizeString(payload === null || payload === void 0 ? void 0 : payload.sourceType, 40).toLowerCase();
    var ignored = normalizeBoolean(payload === null || payload === void 0 ? void 0 : payload.ignored);
    var hasPr = normalizeBoolean(payload === null || payload === void 0 ? void 0 : payload.hasPr);
    if (status && status !== 'all') {
        andClauses.push({ status: status });
    }
    if (sourceType && sourceType !== 'all') {
        andClauses.push({ source_type: sourceType });
    }
    if (typeof ignored === 'boolean') {
        andClauses.push({ ignored: ignored });
    }
    if (typeof hasPr === 'boolean') {
        if (hasPr) {
            andClauses.push({ pr_url: { $exists: true, $nin: ['', null] } });
        }
        else {
            andClauses.push({
                $or: [
                    { pr_url: { $exists: false } },
                    { pr_url: '' },
                    { pr_url: null }
                ]
            });
        }
    }
    var search = normalizeString(payload === null || payload === void 0 ? void 0 : payload.search, 160);
    if (search) {
        var searchRegex = {
            $regex: escapeRegex(search),
            $options: 'i'
        };
        andClauses.push({
            $or: [
                { subject: searchRegex },
                { status: searchRegex },
                { client_name: searchRegex },
                { source_type: searchRegex },
                { source_app: searchRegex },
                { source_environment: searchRegex },
                { severity: searchRegex },
                { branch_name: searchRegex },
                { pr_url: searchRegex },
                { openai_task_id: searchRegex },
                { plan_summary: searchRegex },
                { last_error: searchRegex },
                { autofix_error_count_string: searchRegex }
            ]
        });
    }
    if (!andClauses.length) {
        return query;
    }
    if (andClauses.length === 1) {
        return andClauses[0];
    }
    query.$and = andClauses;
    return query;
}
function buildSlowQuerySearchQuery(payload) {
    var query = {};
    var andClauses = [];
    var status = normalizeString(payload === null || payload === void 0 ? void 0 : payload.status, 40).toLowerCase();
    var verificationStatus = normalizeString(payload === null || payload === void 0 ? void 0 : payload.verificationStatus, 40).toLowerCase();
    var ignored = normalizeBoolean(payload === null || payload === void 0 ? void 0 : payload.ignored);
    var collection = normalizeString(payload === null || payload === void 0 ? void 0 : payload.collection, 120);
    var environment = normalizeString(payload === null || payload === void 0 ? void 0 : payload.environment, 120);
    var clientSlug = normalizeString(payload === null || payload === void 0 ? void 0 : payload.clientSlug, 120);
    var minDurationMs = Number(payload === null || payload === void 0 ? void 0 : payload.minDurationMs);
    if (status && status !== 'all') {
        andClauses.push({ status: status });
    }
    if (verificationStatus && verificationStatus !== 'all') {
        andClauses.push({ verification_status: verificationStatus });
    }
    if (typeof ignored === 'boolean') {
        andClauses.push({ ignored: ignored });
    }
    if (collection) {
        andClauses.push({ collection: collection });
    }
    if (environment) {
        andClauses.push({ environment: environment });
    }
    if (clientSlug) {
        andClauses.push({ client_slug: clientSlug });
    }
    if (Number.isFinite(minDurationMs) && minDurationMs > 0) {
        andClauses.push({
            duration_ms: {
                $gte: Math.floor(minDurationMs)
            }
        });
    }
    var search = normalizeString(payload === null || payload === void 0 ? void 0 : payload.search, 160);
    if (search) {
        var searchRegex = {
            $regex: escapeRegex(search),
            $options: 'i'
        };
        andClauses.push({
            $or: [
                { query_hash: searchRegex },
                { collection: searchRegex },
                { client_slug: searchRegex },
                { client_name: searchRegex },
                { source_app: searchRegex },
                { environment: searchRegex },
                { node_hostname: searchRegex },
                { verification_notes: searchRegex },
                { openai_task_id: searchRegex },
                { slow_query_count_string: searchRegex }
            ]
        });
    }
    if (!andClauses.length) {
        return query;
    }
    if (andClauses.length === 1) {
        return andClauses[0];
    }
    query.$and = andClauses;
    return query;
}
function buildAiAssistantIssueSearchQuery(payload) {
    var query = {};
    var andClauses = [];
    var status = normalizeString(payload === null || payload === void 0 ? void 0 : payload.status, 40).toLowerCase();
    var source = normalizeString(payload === null || payload === void 0 ? void 0 : payload.source, 40).toLowerCase();
    var remediationStatus = normalizeString(payload === null || payload === void 0 ? void 0 : payload.remediationStatus, 40).toLowerCase();
    var idClient = normalizeString(payload === null || payload === void 0 ? void 0 : payload.id_client, 80);
    var idApp = normalizeString(payload === null || payload === void 0 ? void 0 : payload.id_app, 80);
    if (status && status !== 'all') {
        andClauses.push({ status: status });
    }
    if (source && source !== 'all') {
        andClauses.push({ source: source });
    }
    if (remediationStatus && remediationStatus !== 'all') {
        andClauses.push({ 'metadata.quality_manager.remediation.status': remediationStatus });
    }
    if (idClient) {
        andClauses.push({ id_client: idClient });
    }
    if (idApp) {
        andClauses.push({ id_app: idApp });
    }
    var search = normalizeString(payload === null || payload === void 0 ? void 0 : payload.search, 160);
    if (search) {
        var searchRegex = {
            $regex: escapeRegex(search),
            $options: 'i'
        };
        andClauses.push({
            $or: [
                { reason: searchRegex },
                { status: searchRegex },
                { source: searchRegex },
                { id_conversation: searchRegex },
                { id_message: searchRegex },
                { id_client: searchRegex },
                { id_app: searchRegex },
                { 'metadata.quality_manager.code': searchRegex },
                { 'metadata.quality_manager.remediation.status': searchRegex },
                { 'metadata.quality_manager.remediation.last_error': searchRegex }
            ]
        });
    }
    if (!andClauses.length) {
        return query;
    }
    if (andClauses.length === 1) {
        return andClauses[0];
    }
    query.$and = andClauses;
    return query;
}
function getCollection(name) {
    var db = resolveio_server_app_1.ResolveIOServer.getMainDB();
    if (!db) {
        throw new Error('Main DB is not available.');
    }
    return db.collection(name);
}
function loadDiagnosticMethods(methodManager) {
    methodManager.methods({
        superAdminListAutoFixLogs: {
            check: new simpl_schema_1.default({
                payload: {
                    type: Object,
                    optional: true,
                    blackbox: true
                }
            }),
            function: function () {
                return __awaiter(this, arguments, void 0, function (payload) {
                    var query, limit, skip, sortField, sortDirection, sort, collection, _a, items, total;
                    var _b;
                    if (payload === void 0) { payload = {}; }
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _c.sent();
                                query = buildAutoFixSearchQuery(payload);
                                limit = normalizeLimit(payload === null || payload === void 0 ? void 0 : payload.limit);
                                skip = normalizeSkip(payload === null || payload === void 0 ? void 0 : payload.skip);
                                sortField = resolveSortField(payload === null || payload === void 0 ? void 0 : payload.sortField, [
                                    'createdAt',
                                    'updatedAt',
                                    'status',
                                    'duplicate_count',
                                    'attempt_count',
                                    'last_attempt_at',
                                    'last_result_at',
                                    'last_reported_at',
                                    'autofix_error_count'
                                ], 'last_reported_at');
                                sortDirection = normalizeSortDirection(payload === null || payload === void 0 ? void 0 : payload.sortDirection);
                                sort = (_b = {},
                                    _b[sortField] = sortDirection,
                                    _b.updatedAt = -1,
                                    _b);
                                collection = getCollection('error-autofix-logs');
                                return [4 /*yield*/, Promise.all([
                                        collection.find(query).sort(sort).skip(skip).limit(limit).toArray(),
                                        collection.countDocuments(query)
                                    ])];
                            case 2:
                                _a = __read.apply(void 0, [_c.sent(), 2]), items = _a[0], total = _a[1];
                                return [2 /*return*/, {
                                        items: items,
                                        total: total,
                                        limit: limit,
                                        skip: skip
                                    }];
                        }
                    });
                });
            }
        },
        superAdminRunAutoFixLog: {
            check: new simpl_schema_1.default({
                logId: {
                    type: String
                }
            }),
            function: function (logId) {
                return __awaiter(this, void 0, void 0, function () {
                    var manager, result;
                    var _a, _b, _c, _d;
                    return __generator(this, function (_e) {
                        switch (_e.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _e.sent();
                                manager = resolveio_server_app_1.ResolveIOServer['AutoFixManager'];
                                if (!manager || typeof manager.runLog !== 'function') {
                                    throw new Error('Auto-fix manager is not available.');
                                }
                                return [4 /*yield*/, manager.runLog(logId)];
                            case 2:
                                result = _e.sent();
                                return [2 /*return*/, {
                                        status: (result === null || result === void 0 ? void 0 : result.status) || 'unknown',
                                        reason: (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        error: (result === null || result === void 0 ? void 0 : result.error) || '',
                                        logId: ((_a = result === null || result === void 0 ? void 0 : result.log) === null || _a === void 0 ? void 0 : _a._id) || logId,
                                        branchName: (result === null || result === void 0 ? void 0 : result.branchName) || ((_b = result === null || result === void 0 ? void 0 : result.log) === null || _b === void 0 ? void 0 : _b.branch_name) || '',
                                        prUrl: (result === null || result === void 0 ? void 0 : result.prUrl) || ((_c = result === null || result === void 0 ? void 0 : result.log) === null || _c === void 0 ? void 0 : _c.pr_url) || '',
                                        taskId: ((_d = result === null || result === void 0 ? void 0 : result.log) === null || _d === void 0 ? void 0 : _d.openai_task_id) || ''
                                    }];
                        }
                    });
                });
            }
        },
        superAdminListAiAssistantIssueReports: {
            check: new simpl_schema_1.default({
                payload: {
                    type: Object,
                    optional: true,
                    blackbox: true
                }
            }),
            function: function () {
                return __awaiter(this, arguments, void 0, function (payload) {
                    var query, limit, skip, sortField, sortDirection, sort, collection, _a, items, total;
                    var _b;
                    if (payload === void 0) { payload = {}; }
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _c.sent();
                                query = buildAiAssistantIssueSearchQuery(payload);
                                limit = normalizeLimit(payload === null || payload === void 0 ? void 0 : payload.limit);
                                skip = normalizeSkip(payload === null || payload === void 0 ? void 0 : payload.skip);
                                sortField = resolveSortField(payload === null || payload === void 0 ? void 0 : payload.sortField, [
                                    'createdAt',
                                    'updatedAt',
                                    'status',
                                    'source',
                                    'id_client',
                                    'id_app'
                                ], 'updatedAt');
                                sortDirection = normalizeSortDirection(payload === null || payload === void 0 ? void 0 : payload.sortDirection);
                                sort = (_b = {},
                                    _b[sortField] = sortDirection,
                                    _b.updatedAt = -1,
                                    _b);
                                collection = getCollection('ai-terminal-issue-reports');
                                return [4 /*yield*/, Promise.all([
                                        collection.find(query).sort(sort).skip(skip).limit(limit).toArray(),
                                        collection.countDocuments(query)
                                    ])];
                            case 2:
                                _a = __read.apply(void 0, [_c.sent(), 2]), items = _a[0], total = _a[1];
                                return [2 /*return*/, {
                                        items: items,
                                        total: total,
                                        limit: limit,
                                        skip: skip
                                    }];
                        }
                    });
                });
            }
        },
        superAdminRunAiAssistantIssueRemediation: {
            check: new simpl_schema_1.default({
                issueId: {
                    type: String
                },
                force: {
                    type: Boolean,
                    optional: true
                }
            }),
            function: function (issueId, force) {
                return __awaiter(this, void 0, void 0, function () {
                    var manager, result;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _a.sent();
                                manager = resolveio_server_app_1.ResolveIOServer['AiAssistantCodexManager'];
                                if (!manager || typeof manager.runIssueRemediation !== 'function') {
                                    throw new Error('AI assistant Codex manager is not available.');
                                }
                                return [4 /*yield*/, manager.runIssueRemediation(issueId, {
                                        force: !!force,
                                        source: 'manual',
                                        trigger: 'super_admin'
                                    })];
                            case 2:
                                result = _a.sent();
                                return [2 /*return*/, {
                                        status: (result === null || result === void 0 ? void 0 : result.status) || 'unknown',
                                        reason: (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        issueId: (result === null || result === void 0 ? void 0 : result.issueId) || issueId,
                                        attemptCount: Number((result === null || result === void 0 ? void 0 : result.attemptCount) || 0),
                                        durationMs: Number((result === null || result === void 0 ? void 0 : result.durationMs) || 0),
                                        exitCode: typeof (result === null || result === void 0 ? void 0 : result.exitCode) === 'number' ? result.exitCode : null
                                    }];
                        }
                    });
                });
            }
        },
        superAdminRunAiAssistantIssueReplay: {
            check: new simpl_schema_1.default({
                issueId: {
                    type: String
                },
                force: {
                    type: Boolean,
                    optional: true
                }
            }),
            function: function (issueId, force) {
                return __awaiter(this, void 0, void 0, function () {
                    var manager, result;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _a.sent();
                                manager = resolveio_server_app_1.ResolveIOServer['AiAssistantCodexManager'];
                                if (!manager || typeof manager.runIssueReplay !== 'function') {
                                    throw new Error('AI assistant Codex manager is not available.');
                                }
                                return [4 /*yield*/, manager.runIssueReplay(issueId, {
                                        force: !!force,
                                        source: 'manual',
                                        trigger: 'super_admin'
                                    })];
                            case 2:
                                result = _a.sent();
                                return [2 /*return*/, {
                                        status: (result === null || result === void 0 ? void 0 : result.status) || 'unknown',
                                        reason: (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        issueId: (result === null || result === void 0 ? void 0 : result.issueId) || issueId,
                                        attemptCount: Number((result === null || result === void 0 ? void 0 : result.attemptCount) || 0),
                                        durationMs: Number((result === null || result === void 0 ? void 0 : result.durationMs) || 0),
                                        exitCode: typeof (result === null || result === void 0 ? void 0 : result.exitCode) === 'number' ? result.exitCode : null
                                    }];
                        }
                    });
                });
            }
        },
        superAdminListSlowQueryLogs: {
            check: new simpl_schema_1.default({
                payload: {
                    type: Object,
                    optional: true,
                    blackbox: true
                }
            }),
            function: function () {
                return __awaiter(this, arguments, void 0, function (payload) {
                    var query, limit, skip, sortField, sortDirection, sort, collection, _a, items, total;
                    var _b;
                    if (payload === void 0) { payload = {}; }
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _c.sent();
                                query = buildSlowQuerySearchQuery(payload);
                                limit = normalizeLimit(payload === null || payload === void 0 ? void 0 : payload.limit);
                                skip = normalizeSkip(payload === null || payload === void 0 ? void 0 : payload.skip);
                                sortField = resolveSortField(payload === null || payload === void 0 ? void 0 : payload.sortField, [
                                    'createdAt',
                                    'updatedAt',
                                    'collection',
                                    'status',
                                    'verification_status',
                                    'duration_ms',
                                    'avg_duration_ms',
                                    'max_duration_ms',
                                    'occurrences',
                                    'last_seen_at',
                                    'slow_query_count'
                                ], 'last_seen_at');
                                sortDirection = normalizeSortDirection(payload === null || payload === void 0 ? void 0 : payload.sortDirection);
                                sort = (_b = {},
                                    _b[sortField] = sortDirection,
                                    _b.updatedAt = -1,
                                    _b);
                                collection = getCollection('slow-query-logs');
                                return [4 /*yield*/, Promise.all([
                                        collection.find(query).sort(sort).skip(skip).limit(limit).toArray(),
                                        collection.countDocuments(query)
                                    ])];
                            case 2:
                                _a = __read.apply(void 0, [_c.sent(), 2]), items = _a[0], total = _a[1];
                                return [2 /*return*/, {
                                        items: items,
                                        total: total,
                                        limit: limit,
                                        skip: skip
                                    }];
                        }
                    });
                });
            }
        },
        superAdminRunSlowQueryLog: {
            check: new simpl_schema_1.default({
                logId: {
                    type: String
                }
            }),
            function: function (logId) {
                return __awaiter(this, void 0, void 0, function () {
                    var verifier, result;
                    var _a, _b, _c;
                    return __generator(this, function (_d) {
                        switch (_d.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _d.sent();
                                verifier = resolveio_server_app_1.ResolveIOServer['SlowQueryVerifier'];
                                if (!verifier || typeof verifier.queueLogRun !== 'function') {
                                    throw new Error('Slow query verifier is not available.');
                                }
                                return [4 /*yield*/, verifier.queueLogRun(logId, {
                                        force: true
                                    })];
                            case 2:
                                result = _d.sent();
                                return [2 /*return*/, {
                                        status: (result === null || result === void 0 ? void 0 : result.status) || 'unknown',
                                        reason: (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        logId: ((_a = result === null || result === void 0 ? void 0 : result.log) === null || _a === void 0 ? void 0 : _a._id) || logId,
                                        taskId: ((_b = result === null || result === void 0 ? void 0 : result.log) === null || _b === void 0 ? void 0 : _b.openai_task_id) || '',
                                        notes: ((_c = result === null || result === void 0 ? void 0 : result.log) === null || _c === void 0 ? void 0 : _c.verification_notes) || (result === null || result === void 0 ? void 0 : result.reason) || ''
                                    }];
                        }
                    });
                });
            }
        },
        superAdminDeploySlowQueryLog: {
            check: new simpl_schema_1.default({
                logId: {
                    type: String
                }
            }),
            function: function (logId) {
                return __awaiter(this, void 0, void 0, function () {
                    var verifier, result;
                    var _a, _b, _c, _d, _e, _f, _g;
                    return __generator(this, function (_h) {
                        switch (_h.label) {
                            case 0: return [4 /*yield*/, assertSuperAdmin(this)];
                            case 1:
                                _h.sent();
                                verifier = resolveio_server_app_1.ResolveIOServer['SlowQueryVerifier'];
                                if (!verifier || typeof verifier.deployLog !== 'function') {
                                    throw new Error('Slow query verifier is not available.');
                                }
                                return [4 /*yield*/, verifier.deployLog(logId)];
                            case 2:
                                result = _h.sent();
                                return [2 /*return*/, {
                                        status: (result === null || result === void 0 ? void 0 : result.status) || 'unknown',
                                        reason: (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        logId: ((_a = result === null || result === void 0 ? void 0 : result.log) === null || _a === void 0 ? void 0 : _a._id) || logId,
                                        taskId: ((_b = result === null || result === void 0 ? void 0 : result.log) === null || _b === void 0 ? void 0 : _b.openai_task_id) || '',
                                        notes: ((_c = result === null || result === void 0 ? void 0 : result.log) === null || _c === void 0 ? void 0 : _c.verification_notes) || (result === null || result === void 0 ? void 0 : result.reason) || '',
                                        branchName: ((_e = (_d = result === null || result === void 0 ? void 0 : result.log) === null || _d === void 0 ? void 0 : _d.auto_fix_result) === null || _e === void 0 ? void 0 : _e.publish_branch) || '',
                                        publishMessage: ((_g = (_f = result === null || result === void 0 ? void 0 : result.log) === null || _f === void 0 ? void 0 : _f.auto_fix_result) === null || _g === void 0 ? void 0 : _g.publish_message) || ''
                                    }];
                        }
                    });
                });
            }
        }
    });
}

//# sourceMappingURL=diagnostics.js.map
