"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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAgentLogsRoutes = registerAgentLogsRoutes;
const fs = __importStar(require("fs"));
const config_1 = require("../config");
const auth_1 = require("../middleware/auth");
const resourceOwnership_1 = require("../services/resourceOwnership");
const sessionLogger_1 = require("../services/sessionLogger");
const logger_1 = require("../utils/logger");
const agentMetrics_1 = require("../agentv3/agentMetrics");
function registerAgentLogsRoutes(router) {
    router.use('/logs', (_req, res, next) => {
        if (!config_1.featureFlagsConfig.enableAgentLogsApi) {
            return res.status(503).json({
                success: false,
                error: 'Agent logs API is disabled by FEATURE_AGENT_LOGS_API',
                code: 'FEATURE_DISABLED',
            });
        }
        next();
    });
    router.use('/logs', (req, res, next) => {
        if (!(0, resourceOwnership_1.isPrivilegedRequestContext)((0, auth_1.requireRequestContext)(req))) {
            return (0, resourceOwnership_1.sendResourceNotFound)(res);
        }
        next();
    });
    router.get('/logs', (_req, res) => {
        try {
            const manager = (0, sessionLogger_1.getSessionLoggerManager)();
            const sessions = manager.listSessions();
            res.json({
                success: true,
                logDir: manager.getLogDir(),
                sessions,
                count: sessions.length,
            });
        }
        catch (error) {
            res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
    router.get('/logs/:sessionId', (req, res) => {
        const { sessionId } = req.params;
        const { level, component, search, limit } = req.query;
        try {
            const manager = (0, sessionLogger_1.getSessionLoggerManager)();
            const logs = manager.readSessionLogs(sessionId, {
                level: level,
                component: component,
                search: search,
                limit: limit ? parseInt(limit, 10) : undefined,
            });
            res.json({
                success: true,
                sessionId,
                logs,
                count: logs.length,
            });
        }
        catch (error) {
            res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
    router.get('/logs/:sessionId/errors', (req, res) => {
        const { sessionId } = req.params;
        try {
            const manager = (0, sessionLogger_1.getSessionLoggerManager)();
            const logs = manager.readSessionLogs(sessionId, {
                level: ['error', 'warn'],
            });
            res.json({
                success: true,
                sessionId,
                logs,
                errorCount: logs.filter((l) => l.level === 'error').length,
                warnCount: logs.filter((l) => l.level === 'warn').length,
            });
        }
        catch (error) {
            res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
    // ─── Runtime log level management ───────────────────────────────────
    router.get('/admin/log-level', (_req, res) => {
        res.json({
            success: true,
            level: (0, logger_1.getLogLevel)(),
            envDefault: (process.env.LOG_LEVEL || 'info').toLowerCase(),
        });
    });
    router.put('/admin/log-level', (req, res) => {
        const { level } = req.body;
        try {
            (0, logger_1.setLogLevel)(level === null ? null : level);
            res.json({
                success: true,
                level: (0, logger_1.getLogLevel)(),
                message: level === null
                    ? 'Reverted to env var default'
                    : `Log level set to '${level}'`,
            });
        }
        catch (error) {
            res.status(400).json({
                success: false,
                error: error.message,
            });
        }
    });
    // ─── Cross-session metrics aggregation ──────────────────────────────
    router.get('/logs/metrics/summary', (req, res) => {
        const { days = '7' } = req.query;
        const maxAgeDays = parseInt(days, 10) || 7;
        try {
            let files;
            try {
                files = fs.readdirSync(agentMetrics_1.METRICS_DIR).filter(f => f.endsWith('_metrics.json'));
            }
            catch {
                return res.json({ success: true, sessions: 0, summary: null });
            }
            const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
            const allMetrics = [];
            for (const file of files) {
                try {
                    const filePath = `${agentMetrics_1.METRICS_DIR}/${file}`;
                    const stat = fs.statSync(filePath);
                    if (stat.mtimeMs < cutoff)
                        continue;
                    const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
                    allMetrics.push(data);
                }
                catch {
                    // Skip malformed files
                }
            }
            if (allMetrics.length === 0) {
                return res.json({ success: true, sessions: 0, summary: null });
            }
            // Single-pass aggregation
            const durations = [];
            const byTool = {};
            let totalToolCalls = 0;
            let totalToolFailures = 0;
            let totalTurns = 0;
            for (const m of allMetrics) {
                durations.push(m.totalDurationMs);
                totalTurns += m.turns;
                totalToolCalls += m.toolSummary.totalCalls;
                totalToolFailures += m.toolSummary.failureCount;
                for (const [toolName, stats] of Object.entries(m.toolSummary.byTool)) {
                    if (!byTool[toolName]) {
                        byTool[toolName] = { calls: 0, totalMs: 0, failures: 0, avgMsValues: [] };
                    }
                    const entry = byTool[toolName];
                    entry.calls += stats.calls;
                    entry.totalMs += stats.totalMs;
                    entry.failures += stats.failures;
                    // Collect per-session avgMs for percentile (one point per session, not expanded)
                    entry.avgMsValues.push(stats.avgMs);
                }
            }
            durations.sort((a, b) => a - b);
            // Build final per-tool summary
            const byToolSummary = {};
            for (const [toolName, entry] of Object.entries(byTool)) {
                entry.avgMsValues.sort((a, b) => a - b);
                byToolSummary[toolName] = {
                    calls: entry.calls,
                    avgMs: entry.calls > 0 ? Math.round(entry.totalMs / entry.calls) : 0,
                    p50Ms: percentile(entry.avgMsValues, 0.5),
                    p95Ms: percentile(entry.avgMsValues, 0.95),
                    failures: entry.failures,
                };
            }
            res.json({
                success: true,
                sessions: allMetrics.length,
                timeRange: {
                    days: maxAgeDays,
                    from: new Date(cutoff).toISOString(),
                    to: new Date().toISOString(),
                },
                summary: {
                    totalDuration: {
                        avgMs: Math.round(durations.reduce((s, d) => s + d, 0) / durations.length),
                        p50Ms: percentile(durations, 0.5),
                        p95Ms: percentile(durations, 0.95),
                        minMs: durations[0],
                        maxMs: durations[durations.length - 1],
                    },
                    totalTurns,
                    avgTurnsPerSession: Math.round(totalTurns / allMetrics.length * 10) / 10,
                    toolCalls: {
                        total: totalToolCalls,
                        failures: totalToolFailures,
                        failureRate: totalToolCalls > 0 ? Math.round(totalToolFailures / totalToolCalls * 10000) / 100 : 0,
                    },
                    byTool: byToolSummary,
                },
            });
        }
        catch (error) {
            res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
    router.post('/logs/cleanup', (req, res) => {
        const { maxAgeDays = 7 } = req.body;
        try {
            const manager = (0, sessionLogger_1.getSessionLoggerManager)();
            const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
            const deletedCount = manager.cleanup(maxAgeMs);
            res.json({
                success: true,
                deletedCount,
                message: `Deleted ${deletedCount} log files older than ${maxAgeDays} days`,
            });
        }
        catch (error) {
            res.status(500).json({
                success: false,
                error: error.message,
            });
        }
    });
}
/** Nearest-rank percentile from a sorted array (p in 0-1 range). */
function percentile(sorted, p) {
    if (sorted.length === 0)
        return 0;
    const idx = Math.ceil(p * sorted.length) - 1;
    return sorted[Math.max(0, idx)];
}
//# sourceMappingURL=agentLogsRoutes.js.map