"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.registerAgentSessionCatalogRoutes = registerAgentSessionCatalogRoutes;
const enhancedSessionContext_1 = require("../agent/context/enhancedSessionContext");
const sessionPersistenceService_1 = require("../services/sessionPersistenceService");
const auth_1 = require("../middleware/auth");
const resourceOwnership_1 = require("../services/resourceOwnership");
function registerAgentSessionCatalogRoutes(router, deps) {
    router.get('/sessions', async (req, res) => {
        try {
            const requestContext = (0, auth_1.requireRequestContext)(req);
            const { traceId, limit, includeRecoverable } = req.query;
            const parsedLimit = limit ? parseInt(limit, 10) : 20;
            const shouldIncludeRecoverable = includeRecoverable !== 'false';
            const activeSessions = [];
            const activeIds = new Set();
            for (const [sessionId, session] of deps.sessionStore.entries()) {
                if (traceId && session.traceId !== traceId)
                    continue;
                if (!(0, resourceOwnership_1.isOwnedByContext)(session, requestContext))
                    continue;
                const activeContext = enhancedSessionContext_1.sessionContextManager.get(sessionId, session.traceId);
                activeIds.add(sessionId);
                activeSessions.push({
                    sessionId,
                    status: session.status,
                    traceId: session.traceId,
                    query: session.query,
                    createdAt: session.createdAt,
                    isActive: true,
                    turnCount: activeContext?.getAllTurns().length ?? 0,
                    entityStoreStats: null,
                    observability: deps.buildSessionObservability(session),
                });
            }
            const recoverableSessions = [];
            if (shouldIncludeRecoverable) {
                try {
                    const persistenceService = sessionPersistenceService_1.SessionPersistenceService.getInstance();
                    const persistedResult = persistenceService.listSessions({
                        traceId: traceId,
                        limit: parsedLimit,
                    });
                    for (const persistedSession of persistedResult.sessions) {
                        if (activeIds.has(persistedSession.id))
                            continue;
                        if (!persistenceService.hasSessionContext(persistedSession.id))
                            continue;
                        if (!(0, resourceOwnership_1.isOwnedByContext)(persistedSession.metadata, requestContext))
                            continue;
                        const storeStats = persistenceService.getEntityStoreStats(persistedSession.id);
                        const persistedContext = persistenceService.loadSessionContext(persistedSession.id);
                        recoverableSessions.push({
                            sessionId: persistedSession.id,
                            status: 'recoverable',
                            traceId: persistedSession.traceId,
                            traceName: persistedSession.traceName,
                            query: persistedSession.question,
                            createdAt: persistedSession.createdAt,
                            updatedAt: persistedSession.updatedAt,
                            isActive: false,
                            turnCount: persistedContext?.getAllTurns().length ?? 0,
                            entityStoreStats: storeStats,
                        });
                    }
                }
                catch (persistError) {
                    console.warn('[AgentRoutes] Failed to list recoverable sessions:', persistError.message);
                }
            }
            return res.json({
                success: true,
                activeSessions,
                totalActive: activeSessions.length,
                recoverableSessions,
                totalRecoverable: recoverableSessions.length,
            });
        }
        catch (error) {
            return res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
}
//# sourceMappingURL=agentSessionCatalogRoutes.js.map