/**
 * Provider Metrics Routes
 *
 * API endpoint for querying aggregated provider metrics
 * suitable for the web UI and CLI consumption.
 */
import { Hono } from 'hono';
import { createLogger } from '../../utils/logger.js';
const logger = createLogger('metrics-routes');
/**
 * Parse a time range string (e.g., '7d', '14d', '30d') to number of days.
 * Defaults to 7 if invalid.
 */
function parseTimeRange(value) {
    if (!value)
        return 7;
    const match = value.match(/^(\d+)d$/);
    if (match) {
        const days = parseInt(match[1], 10);
        if (days > 0 && days <= 365)
            return days;
    }
    return 7;
}
export function createMetricsRoutes(services) {
    const app = new Hono();
    /**
     * GET /api/provider-metrics
     *
     * Query params:
     *   - timeRange: '7d' | '14d' | '30d' (default: '7d')
     *   - groupBy: 'provider' | 'model' (default: 'provider')
     *   - includeSeries: 'true' | 'false' (default: 'false') — include time-series data
     */
    app.get('/api/provider-metrics', (c) => {
        try {
            const timeRangeParam = c.req.query('timeRange');
            const groupBy = c.req.query('groupBy') || 'provider';
            const includeSeries = c.req.query('includeSeries') === 'true';
            if (groupBy !== 'provider' && groupBy !== 'model') {
                return c.json({ error: { code: 'INVALID_PARAM', message: 'groupBy must be "provider" or "model"' } }, 400);
            }
            const days = parseTimeRange(timeRangeParam);
            const timeRange = { days };
            const aggregated = groupBy === 'provider'
                ? services.metricsService.aggregateByProvider(timeRange)
                : services.metricsService.aggregateByModel(timeRange);
            const result = {
                timeRange: { days, label: `${days}d` },
                groupBy,
                metrics: aggregated,
            };
            if (includeSeries) {
                result.timeSeries = services.metricsService.getTimeSeries(timeRange, groupBy);
            }
            return c.json(result);
        }
        catch (error) {
            logger.error('Failed to get provider metrics:', error);
            return c.json({ error: { code: 'INTERNAL_ERROR', message: String(error) } }, 500);
        }
    });
    return app;
}
//# sourceMappingURL=metrics.js.map