import { httpRequestTotal, httpRequestErrors, runsCreated, runsStarted, runsCompleted, runsActive, sseConnectionsOpened, sseConnectionsClosed, sseActiveConnections, sseMessagesTotal, dbConnectionsActive, dbConnectionsIdle, redisConnectionsActive, } from './index.js';
function sumCounterValues(m) {
    return m.values.reduce((s, x) => s + x.value, 0);
}
function gaugeValue(m) {
    return m.values[0]?.value ?? 0;
}
function isFailedRunStatus(status) {
    const normalized = status.trim().toLowerCase();
    return [
        'failed',
        'failure',
        'error',
        'errored',
        'cancelled',
        'canceled',
        'timeout',
        'timed_out',
    ].includes(normalized);
}
export async function getMonitoringHttpPayload() {
    const req = await httpRequestTotal.get();
    let totalRequests = 0;
    const byRoute = [];
    for (const x of req.values) {
        totalRequests += x.value;
        byRoute.push({
            method: String(x.labels.method ?? ''),
            route: String(x.labels.route ?? ''),
            status_code: String(x.labels.status_code ?? ''),
            count: x.value,
        });
    }
    byRoute.sort((a, b) => b.count - a.count);
    const err = await httpRequestErrors.get();
    let totalErrors = 0;
    const errorsByRoute = [];
    for (const x of err.values) {
        totalErrors += x.value;
        errorsByRoute.push({
            method: String(x.labels.method ?? ''),
            route: String(x.labels.route ?? ''),
            error_type: String(x.labels.error_type ?? ''),
            count: x.value,
        });
    }
    errorsByRoute.sort((a, b) => b.count - a.count);
    const errorRate = totalRequests > 0 ? totalErrors / totalRequests : 0;
    return {
        placeholder: false,
        summary: {
            totalRequests,
            totalErrors,
            errorRate: Number(errorRate.toFixed(4)),
        },
        topRoutes: byRoute.slice(0, 25),
        errorsByRoute: errorsByRoute.slice(0, 15),
        timestamp: new Date().toISOString(),
    };
}
export async function getMonitoringRunsPayload() {
    const created = sumCounterValues(await runsCreated.get());
    const started = sumCounterValues(await runsStarted.get());
    const completedByStatus = (await runsCompleted.get()).values.map((x) => ({
        status: String(x.labels.status ?? ''),
        count: x.value,
    }));
    const completed = completedByStatus.reduce((s, x) => s + x.count, 0);
    const failedByStatus = completedByStatus.filter((x) => isFailedRunStatus(x.status));
    const active = gaugeValue(await runsActive.get());
    return {
        placeholder: false,
        summary: {
            created,
            started,
            completed,
            failed: failedByStatus.reduce((s, x) => s + x.count, 0),
            active,
        },
        byStatus: completedByStatus,
        failedStatusLabels: failedByStatus.map((x) => x.status),
        timestamp: new Date().toISOString(),
    };
}
export async function getMonitoringSsePayload() {
    const opened = sumCounterValues(await sseConnectionsOpened.get());
    const closed = sumCounterValues(await sseConnectionsClosed.get());
    const active = gaugeValue(await sseActiveConnections.get());
    const messages = sumCounterValues(await sseMessagesTotal.get());
    return {
        placeholder: false,
        summary: {
            connectionsOpened: opened,
            connectionsClosed: closed,
            activeConnections: active,
            messagesSent: messages,
        },
        timestamp: new Date().toISOString(),
    };
}
export async function getDependencyPoolsPayload() {
    return {
        database: {
            active: gaugeValue(await dbConnectionsActive.get()),
            idle: gaugeValue(await dbConnectionsIdle.get()),
        },
        redis: {
            active: gaugeValue(await redisConnectionsActive.get()),
        },
        telemetry: {
            source: 'prom-client connection gauges',
            bestEffort: true,
            note: 'Connection gauges are best-effort instrumentation; zeros can mean the gauges are not being updated, not necessarily that dependencies are disconnected.',
        },
    };
}
//# sourceMappingURL=monitoring-detail.js.map