"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentTraceRecorder = void 0;
exports.getAgentTraceRecorder = getAgentTraceRecorder;
exports.resetAgentTraceRecorder = resetAgentTraceRecorder;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
class AgentTraceRecorder {
    constructor(config) {
        this.traces = [];
        this.config = {
            outputDir: config?.outputDir || path_1.default.join(process.cwd(), 'agent-traces'),
            enabled: config?.enabled ?? true,
            maxTraces: config?.maxTraces || 100,
        };
        if (this.config.enabled) {
            this.ensureOutputDir();
        }
    }
    ensureOutputDir() {
        if (!fs_1.default.existsSync(this.config.outputDir)) {
            fs_1.default.mkdirSync(this.config.outputDir, { recursive: true });
        }
    }
    record(query, traceId, orchestratorTrace, confidence) {
        const totalToolCalls = orchestratorTrace.expertTraces.reduce((sum, et) => sum + et.toolCalls.length, 0);
        const recorded = {
            id: `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            timestamp: new Date().toISOString(),
            query,
            traceId,
            orchestratorTrace,
            metadata: {
                totalDurationMs: orchestratorTrace.totalDuration,
                totalLLMCalls: orchestratorTrace.totalLLMCalls,
                totalToolCalls,
                totalFindings: orchestratorTrace.expertTraces.reduce((sum, et) => sum + et.thoughts.filter(t => t.decision === 'conclude').length, 0),
                expertCount: orchestratorTrace.expertTraces.length,
                confidence,
            },
        };
        this.traces.push(recorded);
        if (this.traces.length > this.config.maxTraces) {
            this.traces.shift();
        }
        if (this.config.enabled) {
            this.saveTrace(recorded);
        }
        return recorded;
    }
    saveTrace(trace) {
        const filename = `${trace.id}.json`;
        const filepath = path_1.default.join(this.config.outputDir, filename);
        fs_1.default.writeFileSync(filepath, JSON.stringify(trace, null, 2));
    }
    getTrace(id) {
        return this.traces.find(t => t.id === id);
    }
    getRecentTraces(limit = 10) {
        return this.traces.slice(-limit);
    }
    getStatistics() {
        if (this.traces.length === 0) {
            return {
                totalTraces: 0,
                avgDurationMs: 0,
                avgConfidence: 0,
                avgToolCalls: 0,
                avgLLMCalls: 0,
            };
        }
        const sum = this.traces.reduce((acc, t) => ({
            duration: acc.duration + t.metadata.totalDurationMs,
            confidence: acc.confidence + t.metadata.confidence,
            toolCalls: acc.toolCalls + t.metadata.totalToolCalls,
            llmCalls: acc.llmCalls + t.metadata.totalLLMCalls,
        }), { duration: 0, confidence: 0, toolCalls: 0, llmCalls: 0 });
        const count = this.traces.length;
        return {
            totalTraces: count,
            avgDurationMs: Math.round(sum.duration / count),
            avgConfidence: Math.round((sum.confidence / count) * 100) / 100,
            avgToolCalls: Math.round((sum.toolCalls / count) * 10) / 10,
            avgLLMCalls: Math.round((sum.llmCalls / count) * 10) / 10,
        };
    }
    loadTracesFromDisk() {
        if (!fs_1.default.existsSync(this.config.outputDir))
            return;
        const files = fs_1.default.readdirSync(this.config.outputDir)
            .filter(f => f.endsWith('.json'))
            .sort();
        for (const file of files.slice(-this.config.maxTraces)) {
            try {
                const content = fs_1.default.readFileSync(path_1.default.join(this.config.outputDir, file), 'utf-8');
                const trace = JSON.parse(content);
                this.traces.push(trace);
            }
            catch {
            }
        }
    }
}
exports.AgentTraceRecorder = AgentTraceRecorder;
let globalRecorder = null;
function getAgentTraceRecorder(config) {
    if (!globalRecorder) {
        globalRecorder = new AgentTraceRecorder(config);
        globalRecorder.loadTracesFromDisk();
    }
    return globalRecorder;
}
function resetAgentTraceRecorder() {
    globalRecorder = null;
}
//# sourceMappingURL=traceRecorder.js.map