{% extends "base.html" %}

{% block content %}
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-label">Total Requests</div>
        <div class="stat-value">{{ stats.total_requests | default(0) }}</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Total Cost</div>
        <div class="stat-value">${{ "%.4f" | format(stats.total_cost | default(0) | float) }}</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Input Tokens</div>
        <div class="stat-value">{{ "{:,}".format(stats.total_input_tokens | default(0) | int) }}</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Output Tokens</div>
        <div class="stat-value">{{ "{:,}".format(stats.total_output_tokens | default(0) | int) }}</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Total Tokens</div>
        <div class="stat-value">{{ "{:,}".format(stats.total_tokens | default(0) | int) }}</div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Avg Latency</div>
        <div class="stat-value">{{ "%.0f" | format(stats.avg_duration_ms | default(0) | float) }}ms</div>
    </div>
</div>

{# ── Usage Over Time Chart ── #}
{% if daily_usage %}
<section class="card">
    <div class="card-header">
        <h3>Usage Over Time</h3>
        <div class="chart-controls">
            <select id="analyticsUsageMetric" onchange="updateAnalyticsChart()">
                <option value="cost" selected>Cost ($)</option>
                <option value="tokens">Total Tokens</option>
                <option value="requests">Requests</option>
            </select>
        </div>
    </div>
    <div class="usage-chart-container">
        <canvas id="analyticsUsageChart"></canvas>
    </div>
</section>
<script>
(function() {
    var dailyData = {{ daily_usage | tojson }};
    var labels = dailyData.map(function(d) { return d.day; });
    var datasets = {
        cost: dailyData.map(function(d) { return parseFloat(d.total_cost) || 0; }),
        tokens: dailyData.map(function(d) { return parseInt(d.total_tokens) || 0; }),
        requests: dailyData.map(function(d) { return parseInt(d.request_count) || 0; })
    };
    var colors = {
        cost: { bg: 'rgba(74, 108, 247, 0.7)', border: 'rgba(74, 108, 247, 1)' },
        tokens: { bg: 'rgba(245, 158, 11, 0.7)', border: 'rgba(245, 158, 11, 1)' },
        requests: { bg: 'rgba(16, 185, 129, 0.7)', border: 'rgba(16, 185, 129, 1)' }
    };
    var chartLabels = { cost: 'Cost ($)', tokens: 'Total Tokens', requests: 'Requests' };
    var ctx = document.getElementById('analyticsUsageChart').getContext('2d');
    var chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: chartLabels.cost,
                data: datasets.cost,
                backgroundColor: colors.cost.bg,
                borderColor: colors.cost.border,
                borderWidth: 1,
                borderRadius: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            var metric = document.getElementById('analyticsUsageMetric').value;
                            if (metric === 'cost') return '$' + ctx.parsed.y.toFixed(6);
                            return ctx.parsed.y.toLocaleString();
                        }
                    }
                }
            },
            scales: {
                x: { grid: { display: false }, ticks: { font: { size: 11 } } },
                y: {
                    beginAtZero: true,
                    grid: { color: '#e2e8f0' },
                    ticks: {
                        font: { size: 11 },
                        callback: function(v) {
                            var metric = document.getElementById('analyticsUsageMetric').value;
                            if (metric === 'cost') return '$' + v.toFixed(4);
                            if (v >= 1000) return (v / 1000).toFixed(1) + 'k';
                            return v;
                        }
                    }
                }
            }
        }
    });
    window.updateAnalyticsChart = function() {
        var metric = document.getElementById('analyticsUsageMetric').value;
        chart.data.datasets[0].data = datasets[metric];
        chart.data.datasets[0].label = chartLabels[metric];
        chart.data.datasets[0].backgroundColor = colors[metric].bg;
        chart.data.datasets[0].borderColor = colors[metric].border;
        chart.update();
    };
})();
</script>
{% endif %}

{% if models %}
<section class="card">
    <div class="card-header">
        <h3>Model Breakdown</h3>
        <a href="/analytics/models" class="link-small">View all</a>
    </div>
    <table class="data-table">
        <thead>
            <tr>
                <th>Model</th>
                <th>Requests</th>
                <th>Input Tokens</th>
                <th>Output Tokens</th>
                <th>Cached Tokens</th>
                <th>Total Tokens</th>
                <th>Cost</th>
                <th>Avg Latency</th>
            </tr>
        </thead>
        <tbody>
            {% for m in models %}
            <tr>
                <td>{{ m.model }}</td>
                <td>{{ m.request_count }}</td>
                <td>{{ "{:,}".format(m.total_input_tokens | default(0) | int) }}{% if m.total_input_cost %} <span class="cost-inline">(${{ "%.4f" | format(m.total_input_cost | float) }})</span>{% endif %}</td>
                <td>{{ "{:,}".format(m.total_output_tokens | default(0) | int) }}{% if m.total_output_cost %} <span class="cost-inline">(${{ "%.4f" | format(m.total_output_cost | float) }})</span>{% endif %}</td>
                <td>{{ "{:,}".format(m.total_cached_tokens | default(0) | int) }}{% if m.total_cached_cost %} <span class="cost-inline">(${{ "%.4f" | format(m.total_cached_cost | float) }})</span>{% endif %}</td>
                <td>{{ "{:,}".format(m.total_tokens | default(0) | int) }}</td>
                <td>${{ "%.4f" | format(m.total_cost | default(0) | float) }}</td>
                <td>{{ "%.0f" | format(m.avg_duration_ms | default(0) | float) }}ms</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</section>
{% endif %}

{% if agents %}
<section class="card">
    <div class="card-header">
        <h3>Agent Breakdown</h3>
        <a href="/analytics/agents" class="link-small">View all</a>
    </div>
    <table class="data-table">
        <thead>
            <tr>
                <th>Agent</th>
                <th>Requests</th>
                <th>Input Tokens</th>
                <th>Output Tokens</th>
                <th>Total Tokens</th>
                <th>Cost</th>
                <th>Avg Latency</th>
            </tr>
        </thead>
        <tbody>
            {% for a in agents %}
            <tr>
                <td>{{ a.component_name | default(a.component_class) }}</td>
                <td>{{ a.request_count }}</td>
                <td>{{ "{:,}".format(a.total_input_tokens | default(0) | int) }}</td>
                <td>{{ "{:,}".format(a.total_output_tokens | default(0) | int) }}</td>
                <td>{{ "{:,}".format(a.total_tokens | default(0) | int) }}</td>
                <td>${{ "%.4f" | format(a.total_cost | default(0) | float) }}</td>
                <td>{{ "%.0f" | format(a.avg_duration_ms | default(0) | float) }}ms</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</section>
{% endif %}
{% endblock %}
