import { getQueue } from '../queue/index.js';
import { performHealthChecks } from '../health/index.js';
import { createLogger } from '@4runr/shared';
import { wrapLoggerForMonitoring } from '../middleware/log-capture.js';
import { getDependencyPoolsPayload, getMonitoringHttpPayload, getMonitoringRunsPayload, getMonitoringSsePayload, } from '../metrics/monitoring-detail.js';
const LOG_BUFFER_SIZE = 1000;
const logBuffer = [];
export function addMonitoringLog(entry) {
    logBuffer.push(entry);
    if (logBuffer.length > LOG_BUFFER_SIZE) {
        logBuffer.shift();
    }
}
export function registerMonitoringRoutes(fastify, options) {
    const { requireAuth, readRateLimit } = options || {};
    const logger = wrapLoggerForMonitoring(createLogger('Gateway:Monitoring'));
    const authHandler = requireAuth === false ? null : requireAuth;
    const preHandler = authHandler && readRateLimit
        ? [authHandler, readRateLimit]
        : authHandler
            ? [authHandler]
            : [];
    fastify.get('/api/monitoring/logs', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (request, reply) => {
        const query = request.query;
        const limit = Math.min(parseInt(query.limit || '100', 10), LOG_BUFFER_SIZE);
        const levelFilter = query.level;
        let logs = logBuffer.slice(-limit);
        if (levelFilter) {
            logs = logs.filter(log => log.level === levelFilter);
        }
        return {
            logs,
            count: logs.length,
            bufferSize: logBuffer.length,
            timestamp: new Date().toISOString(),
        };
    });
    fastify.get('/api/monitoring/dependencies/detail', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (request, reply) => {
        const health = await performHealthChecks();
        const details = {};
        const pools = await getDependencyPoolsPayload();
        if (health.checks.database) {
            const dbLatency = health.checks.database.responseTime;
            details.database = {
                status: health.checks.database.status,
                ...(dbLatency !== undefined && { latency: dbLatency }),
                poolAvailable: true,
                pool: {
                    active: pools.database.active,
                    idle: pools.database.idle,
                },
                telemetry: pools.telemetry,
            };
        }
        if (health.checks.redis) {
            const redisLatency = health.checks.redis.responseTime;
            details.redis = {
                status: health.checks.redis.status,
                ...(redisLatency !== undefined && { latency: redisLatency }),
                connectionCountAvailable: true,
                connections: {
                    active: pools.redis.active,
                },
                telemetry: pools.telemetry,
            };
        }
        if (health.checks.queue) {
            details.queue = {
                status: health.checks.queue.status,
            };
            try {
                const queue = getQueue();
                if (queue) {
                    const counts = await queue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed');
                    details.queue.jobs = {
                        waiting: counts['waiting'] ?? 0,
                        active: counts['active'] ?? 0,
                        completed: counts['completed'] ?? 0,
                        failed: counts['failed'] ?? 0,
                        delayed: counts['delayed'] ?? 0,
                    };
                }
            }
            catch (err) {
                logger.error('Failed to fetch queue job counts', {
                    error: err instanceof Error ? err.message : String(err),
                });
            }
        }
        if (health.checks.shield) {
            details.shield = health.checks.shield;
        }
        return {
            details,
            telemetry: pools.telemetry,
            timestamp: new Date().toISOString(),
        };
    });
    fastify.get('/api/monitoring/metrics/http', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (_request, _reply) => {
        return await getMonitoringHttpPayload();
    });
    fastify.get('/api/monitoring/metrics/runs', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (_request, _reply) => {
        return await getMonitoringRunsPayload();
    });
    fastify.get('/api/monitoring/metrics/sse', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (_request, _reply) => {
        return await getMonitoringSsePayload();
    });
    fastify.get('/api/monitoring/metrics/queue', {
        ...(preHandler.length > 0 && { preHandler }),
    }, async (request, reply) => {
        try {
            const queue = getQueue();
            if (!queue) {
                return {
                    available: false,
                    message: 'Queue not initialized (Redis required)',
                    timestamp: new Date().toISOString(),
                };
            }
            const counts = await queue.getJobCounts('waiting', 'active', 'completed', 'failed', 'delayed', 'paused');
            return {
                available: true,
                jobs: {
                    waiting: counts['waiting'] ?? 0,
                    active: counts['active'] ?? 0,
                    completed: counts['completed'] ?? 0,
                    failed: counts['failed'] ?? 0,
                    delayed: counts['delayed'] ?? 0,
                    paused: counts['paused'] ?? 0,
                },
                queueName: queue.name || 'run-execution',
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            logger.error('Failed to get queue metrics', {
                error: error instanceof Error ? error.message : String(error),
            });
            return {
                available: false,
                error: error instanceof Error ? error.message : String(error),
                timestamp: new Date().toISOString(),
            };
        }
    });
    logger.info('Monitoring routes registered (Phase 0)', {
        authRequired: preHandler.length > 0,
        endpoints: [
            '/api/monitoring/logs',
            '/api/monitoring/dependencies/detail',
            '/api/monitoring/metrics/http',
            '/api/monitoring/metrics/runs',
            '/api/monitoring/metrics/sse',
            '/api/monitoring/metrics/queue',
        ],
    });
}
//# sourceMappingURL=monitoring.js.map