"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.registerAgentReportRoutes = registerAgentReportRoutes;
const sessionPersistenceService_1 = require("../services/sessionPersistenceService");
const auth_1 = require("../middleware/auth");
const resourceOwnership_1 = require("../services/resourceOwnership");
function registerAgentReportRoutes(router, deps) {
    router.get('/:sessionId/report', (req, res) => {
        const { sessionId } = req.params;
        const session = deps.getSession(sessionId);
        if (!session || !(0, resourceOwnership_1.isOwnedByContext)(session, (0, auth_1.requireRequestContext)(req))) {
            return (0, resourceOwnership_1.sendResourceNotFound)(res, 'Session not found');
        }
        if (session.status !== 'completed' && session.status !== 'quota_exceeded') {
            return res.status(400).json({
                success: false,
                error: 'Session is not completed yet',
                status: session.status,
            });
        }
        const result = deps.recoverResultForSessionIfNeeded(sessionId, session);
        if (!result) {
            return res.status(404).json({
                success: false,
                error: 'No completed turn result available for this session',
                hint: `Use /api/agent/v1/${sessionId}/turns to inspect historical turns`,
            });
        }
        const completedPayload = deps.getCompletedPayload?.(session);
        const conclusion = completedPayload?.normalizedConclusion
            || deps.normalizeNarrativeForClient(result.conclusion);
        const findings = Array.isArray(result.findings) ? result.findings : [];
        const clientFindings = deps.buildClientFindings(findings, session.scenes || []);
        const resultContract = deps.buildSessionResultContract(session, clientFindings);
        const hypotheses = Array.isArray(result.hypotheses) ? result.hypotheses : [];
        const conversationTimeline = Array.isArray(session.conversationSteps)
            ? session.conversationSteps
            : [];
        // Use snapshot as single source of truth for agentv3-specific state.
        // Falls back to live getters for active sessions where snapshot hasn't been taken yet.
        const snapshot = sessionPersistenceService_1.SessionPersistenceService.getInstance().loadSessionStateSnapshot(sessionId);
        const analysisNotes = snapshot?.analysisNotes
            ?? (typeof session.orchestrator?.getSessionNotes === 'function'
                ? session.orchestrator.getSessionNotes(sessionId) : []);
        const analysisPlan = snapshot?.analysisPlan
            ?? (typeof session.orchestrator?.getSessionPlan === 'function'
                ? session.orchestrator.getSessionPlan(sessionId) : null);
        const uncertaintyFlags = snapshot?.uncertaintyFlags
            ?? (typeof session.orchestrator?.getSessionUncertaintyFlags === 'function'
                ? session.orchestrator.getSessionUncertaintyFlags(sessionId) : []);
        const report = {
            sessionId,
            traceId: session.traceId,
            query: session.query,
            createdAt: session.createdAt,
            completedAt: Date.now(),
            summary: {
                conclusion,
                confidence: result.confidence,
                totalDurationMs: result.totalDurationMs,
                rounds: result.rounds,
                partial: result.partial,
                terminationReason: result.terminationReason,
                terminationMessage: result.terminationMessage,
            },
            reportUrl: completedPayload?.finalArtifacts?.reportUrl,
            reportError: completedPayload?.finalArtifacts?.reportError,
            resultSnapshotId: completedPayload?.finalArtifacts?.resultSnapshotId,
            claimSupport: completedPayload?.qualityArtifacts?.claimSupport || result.claimSupport,
            claimVerificationResult: completedPayload?.qualityArtifacts?.claimVerificationResult || result.claimVerificationResult,
            identityResolutions: completedPayload?.qualityArtifacts?.identityResolutions || result.identityResolutions,
            findings: findings.map((f) => ({
                id: f.id,
                category: f.category,
                severity: f.severity,
                title: f.title,
                description: f.description,
            })),
            hypotheses: hypotheses.map((h) => ({
                id: h.id,
                description: h.description,
                status: h.status,
                confidence: h.confidence,
            })),
            conversationTimeline: conversationTimeline.map((step) => ({
                eventId: step.eventId,
                ordinal: step.ordinal,
                phase: step.phase,
                role: step.role,
                text: step.text,
                timestamp: step.timestamp,
                sourceEventType: step.sourceEventType,
            })),
            queryHistory: session.queryHistory || [],
            conclusionHistory: session.conclusionHistory || [],
            analysisNotes,
            analysisPlan,
            uncertaintyFlags,
            resultContract,
            logFile: session.logger.getLogFilePath(),
        };
        return res.json({
            success: true,
            report,
        });
    });
}
//# sourceMappingURL=agentReportRoutes.js.map