"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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAgentDrivenReportData = buildAgentDrivenReportData;
const enhancedSessionContext_1 = require("../agent/context/enhancedSessionContext");
const traceProcessorService_1 = require("./traceProcessorService");
function buildAgentDrivenReportData(input) {
    const { session, result } = input;
    // Cumulative findings: dedup across all persisted turns. `session.result`
    // only carries the current turn's findings, but multi-turn reports need
    // the full picture to stay consistent with the timeline section.
    let cumulativeResult = result;
    try {
        const ctx = enhancedSessionContext_1.sessionContextManager.get(session.sessionId, session.traceId);
        if (ctx) {
            const allTurns = ctx.getAllTurns();
            if (allTurns.length > 1) {
                const allFindings = allTurns.flatMap((t) => t.findings || []);
                const seen = new Set();
                const deduped = allFindings.filter((f) => {
                    if (seen.has(f.id))
                        return false;
                    seen.add(f.id);
                    return true;
                });
                cumulativeResult = { ...result, findings: deduped };
            }
        }
    }
    catch {
        // Fallback to current turn only — non-fatal.
    }
    // Empty-conclusion recovery: rare SDK result-message drops leave an empty
    // string even though tokens streamed fine. Use conclusionHistory's latest
    // as a last-resort source of truth.
    if (!cumulativeResult.conclusion || !cumulativeResult.conclusion.trim()) {
        const lastCH = session.conclusionHistory?.length
            ? session.conclusionHistory[session.conclusionHistory.length - 1]
            : null;
        if (lastCH?.conclusion) {
            console.warn('[ReportData] Conclusion empty in result — recovered from conclusionHistory');
            cumulativeResult = { ...cumulativeResult, conclusion: lastCH.conclusion };
        }
    }
    const traceInfo = (0, traceProcessorService_1.getTraceProcessorService)().getTrace(session.traceId);
    const traceStartNs = traceInfo?.metadata?.startTime;
    const snapshot = session._lastSnapshot;
    return {
        traceId: session.traceId,
        query: session.query,
        traceStartNs: traceStartNs !== undefined && traceStartNs !== null ? String(traceStartNs) : undefined,
        result: cumulativeResult,
        hypotheses: session.hypotheses,
        dialogue: session.agentDialogue,
        conversationTimeline: session.conversationSteps,
        dataEnvelopes: session.dataEnvelopes,
        agentResponses: session.agentResponses,
        timestamp: Date.now(),
        conversationTurns: session.runSequence || 1,
        queryHistory: session.queryHistory || [],
        conclusionHistory: session.conclusionHistory || [],
        // Snapshot-first — the HTTP route's persistence step stashes `_lastSnapshot`
        // on the session, the CLI's `persistTurnToBackend` does the same. Callers
        // that skip the snapshot step (tests, partial builds) fall through to
        // the orchestrator getters.
        analysisNotes: snapshot?.analysisNotes
            ?? (typeof session.orchestrator.getSessionNotes === 'function'
                ? session.orchestrator.getSessionNotes(session.sessionId) : []),
        analysisPlan: snapshot?.analysisPlan
            ?? (typeof session.orchestrator.getSessionPlan === 'function'
                ? session.orchestrator.getSessionPlan(session.sessionId) : null),
        uncertaintyFlags: snapshot?.uncertaintyFlags
            ?? (typeof session.orchestrator.getSessionUncertaintyFlags === 'function'
                ? session.orchestrator.getSessionUncertaintyFlags(session.sessionId) : []),
        comparisonReportSection: snapshot?.comparisonReportSection
            ?? session.comparisonReportSection,
    };
}
//# sourceMappingURL=agentReportData.js.map