{% extends "base.html" %}
{% block title %}Traces — {{ project.name }} — evalkit{% endblock %}
{% block content %}
<div class="mb-6">
    <p class="text-sm text-gray-400 mb-1"><a href="/" class="hover:underline">Projects</a> / {{ project.name }}</p>
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-semibold">{{ project.name }}</h1>
    </div>
    {% if project.description %}
    <p class="mt-1 text-sm text-gray-500">{{ project.description }}</p>
    {% endif %}
</div>

<!-- Tabs -->
<div class="flex border-b border-gray-200 mb-6">
    <a href="/projects/{{ project.id }}"
       class="px-5 py-2.5 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">
        Evaluations
    </a>
    <a href="/projects/{{ project.id }}/monitor"
       class="px-5 py-2.5 text-sm font-medium border-b-2 border-indigo-600 text-indigo-600">
        Traces
    </a>
</div>

<!-- Filters -->
<form method="get" class="flex flex-wrap items-center gap-3 mb-6">
    <label class="text-xs text-gray-500 uppercase tracking-wide">Range</label>
    <select name="range" onchange="this.form.submit()"
            class="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white">
        {% for r in ["1h", "6h", "24h", "7d", "30d"] %}
        <option value="{{ r }}" {% if time_range == r %}selected{% endif %}>{{ r }}</option>
        {% endfor %}
    </select>

    <label class="text-xs text-gray-500 uppercase tracking-wide ml-2">Interval</label>
    <select name="interval" onchange="this.form.submit()"
            class="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white">
        {% for iv in ["5m", "15m", "1h", "6h", "1d"] %}
        <option value="{{ iv }}" {% if interval == iv %}selected{% endif %}>{{ iv }}</option>
        {% endfor %}
    </select>

    <label class="text-xs text-gray-500 uppercase tracking-wide ml-2">Aggregation</label>
    <select name="agg" onchange="this.form.submit()"
            class="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white">
        {% for a in ["avg", "min", "max"] %}
        <option value="{{ a }}" {% if agg == a %}selected{% endif %}>{{ a }}</option>
        {% endfor %}
    </select>

    {% if metric_names %}
    <label class="text-xs text-gray-500 uppercase tracking-wide ml-2">Metric</label>
    <select name="metric" onchange="this.form.submit()"
            class="text-sm border border-gray-200 rounded-lg px-3 py-1.5 bg-white">
        <option value="">All</option>
        {% for m in metric_names %}
        <option value="{{ m }}" {% if metric == m %}selected{% endif %}>{{ m }}</option>
        {% endfor %}
    </select>
    {% endif %}
</form>

<!-- Summary cards -->
<div class="grid grid-cols-4 gap-4 mb-6">
    <div class="bg-white rounded-xl border border-gray-200 p-4 text-center">
        <div class="text-2xl font-bold text-gray-800">{{ total }}</div>
        <div class="text-xs text-gray-500 mt-1">Traces</div>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4 text-center">
        {% if chart_scores %}
        {% set avg_val = (chart_scores | sum / chart_scores | length * 100) | round(1) %}
        <div class="text-2xl font-bold {% if avg_val >= 80 %}text-green-600{% elif avg_val >= 50 %}text-yellow-600{% else %}text-red-600{% endif %}">{{ avg_val }}%</div>
        {% else %}
        <div class="text-2xl font-bold text-gray-400">&mdash;</div>
        {% endif %}
        <div class="text-xs text-gray-500 mt-1">Avg Score</div>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4 text-center">
        {% if chart_counts %}
        <div class="text-2xl font-bold text-gray-800">{{ (chart_counts | sum / chart_counts | length) | round(1) }}</div>
        {% else %}
        <div class="text-2xl font-bold text-gray-400">&mdash;</div>
        {% endif %}
        <div class="text-xs text-gray-500 mt-1">Avg / Interval</div>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4 text-center">
        <div class="text-2xl font-bold {% if anomaly_count > 0 %}text-red-600{% else %}text-green-600{% endif %}">{{ anomaly_count }}</div>
        <div class="text-xs text-gray-500 mt-1">Anomalies</div>
    </div>
</div>

<!-- Charts -->
{% if chart_labels | length >= 1 %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
    <!-- Score chart -->
    <div class="bg-white rounded-xl border border-gray-200 p-5">
        <h2 class="text-sm font-semibold text-gray-600 mb-3">Score ({{ agg }})</h2>
        <canvas id="scoreChart" height="140"></canvas>
    </div>
    <!-- Volume chart -->
    <div class="bg-white rounded-xl border border-gray-200 p-5">
        <h2 class="text-sm font-semibold text-gray-600 mb-3">Request Volume</h2>
        <canvas id="volumeChart" height="140"></canvas>
    </div>
</div>
<script>
    const labels = {{ chart_labels | tojson }};
    const scores = {{ chart_scores | tojson }};
    const counts = {{ chart_counts | tojson }};
    const anomalies = {{ chart_anomalies | tojson }};

    // Score chart
    new Chart(document.getElementById('scoreChart').getContext('2d'), {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '{{ agg }} score',
                data: scores,
                borderColor: '#6366f1',
                backgroundColor: 'rgba(99,102,241,0.08)',
                tension: 0.3,
                fill: true,
                pointRadius: scores.map((_, i) => anomalies[i] ? 6 : 3),
                pointBackgroundColor: scores.map((_, i) => anomalies[i] ? '#ef4444' : '#6366f1'),
                pointBorderColor: scores.map((_, i) => anomalies[i] ? '#ef4444' : '#6366f1'),
            }]
        },
        options: {
            scales: { y: { min: 0, max: 1, ticks: { callback: v => (v*100)+'%' } } },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: ctx => (ctx.raw * 100).toFixed(1) + '%' + (anomalies[ctx.dataIndex] ? ' ⚠ anomaly' : '')
                    }
                }
            }
        }
    });

    // Volume chart
    new Chart(document.getElementById('volumeChart').getContext('2d'), {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Traces',
                data: counts,
                backgroundColor: counts.map((_, i) => anomalies[i] ? 'rgba(239,68,68,0.6)' : 'rgba(99,102,241,0.6)'),
                borderRadius: 4,
            }]
        },
        options: {
            scales: { y: { beginAtZero: true, ticks: { precision: 0 } } },
            plugins: { legend: { display: false } }
        }
    });
</script>
{% endif %}

<!-- Traces table -->
{% if traces %}
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
            <tr>
                <th class="px-5 py-3 text-left">Timestamp</th>
                <th class="px-5 py-3 text-left">Question</th>
                <th class="px-5 py-3 text-left">Answer</th>
                <th class="px-5 py-3 text-left">Score</th>
                <th class="px-5 py-3 text-left">Metadata</th>
                <th class="px-5 py-3"></th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
            {% for t in traces %}
            {% set scores_list = t.scores %}
            {% set avg = None %}
            {% if scores_list | length > 0 %}
                {% set avg = (scores_list | map(attribute='score') | sum / scores_list | length * 100) | round(0) | int %}
            {% endif %}
            {% set tc = t.get_test_case() %}
            <tr class="hover:bg-gray-50">
                <td class="px-5 py-3 text-gray-400 whitespace-nowrap">{{ t.timestamp.strftime('%Y-%m-%d %H:%M') }}</td>
                <td class="px-5 py-3 max-w-[200px] truncate" title="{{ tc.get('question', '') }}">{{ tc.get('question', '') }}</td>
                <td class="px-5 py-3 max-w-[200px] truncate text-gray-500" title="{{ tc.get('answer', '') }}">{{ tc.get('answer', '') }}</td>
                <td class="px-5 py-3">
                    {% if avg is not none %}
                    <span class="font-semibold {% if avg >= 80 %}text-green-600{% elif avg >= 50 %}text-yellow-600{% else %}text-red-600{% endif %}">{{ avg }}%</span>
                    {% if t.id in trace_anomaly_ids %}
                    <span class="ml-1 px-1.5 py-0.5 rounded text-xs font-medium bg-red-100 text-red-700">anomaly</span>
                    {% endif %}
                    {% else %}&mdash;{% endif %}
                </td>
                <td class="px-5 py-3">
                    {% for k, v in t.get_metadata().items() %}
                    <span class="inline-block bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded mr-1">{{ k }}={{ v }}</span>
                    {% endfor %}
                </td>
                <td class="px-5 py-3 text-right">
                    <a href="/traces/{{ t.id }}" class="text-indigo-600 hover:underline text-xs">View</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

{% macro qs(p=page) %}range={{ time_range }}&interval={{ interval }}&agg={{ agg }}&per_page={{ per_page }}{% if metric %}&metric={{ metric }}{% endif %}&page={{ p }}{% endmacro %}

<div class="flex items-center justify-between mt-4 text-sm">
    <div class="flex items-center gap-3">
        <span class="text-gray-500">{{ total }} trace{{ 's' if total != 1 }} — page {{ page }} of {{ total_pages }}</span>
        <form method="get" class="flex items-center gap-1">
            <input type="hidden" name="range" value="{{ time_range }}">
            <input type="hidden" name="interval" value="{{ interval }}">
            <input type="hidden" name="agg" value="{{ agg }}">
            {% if metric %}<input type="hidden" name="metric" value="{{ metric }}">{% endif %}
            <input type="hidden" name="page" value="1">
            <label class="text-xs text-gray-400">Show</label>
            <select name="per_page" onchange="this.form.submit()"
                    class="text-xs border border-gray-200 rounded px-2 py-1 bg-white">
                {% for opt in per_page_options %}
                <option value="{{ opt }}" {% if per_page == opt %}selected{% endif %}>{{ opt }}</option>
                {% endfor %}
            </select>
        </form>
    </div>
    {% if total_pages > 1 %}
    <div class="flex gap-1">
        {% if page > 1 %}
        <a href="?{{ qs(page - 1) }}" class="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50">Prev</a>
        {% endif %}
        {% for p in range(1, total_pages + 1) %}
            {% if p == page %}
            <span class="px-3 py-1.5 rounded-lg bg-indigo-600 text-white font-medium">{{ p }}</span>
            {% elif p == 1 or p == total_pages or (p >= page - 1 and p <= page + 1) %}
            <a href="?{{ qs(p) }}" class="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50">{{ p }}</a>
            {% elif p == 2 or p == total_pages - 1 %}
            <span class="px-2 py-1.5 text-gray-400">&hellip;</span>
            {% endif %}
        {% endfor %}
        {% if page < total_pages %}
        <a href="?{{ qs(page + 1) }}" class="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50">Next</a>
        {% endif %}
    </div>
    {% endif %}
</div>

{% else %}
<div class="text-center py-12 text-gray-400 bg-white rounded-xl border border-gray-200">
    <p class="text-3xl mb-3">&#128200;</p>
    <p class="font-medium">No traces yet</p>
    <p class="text-sm mt-1">Push traces from your application using the SDK.</p>
    <pre class="mt-4 bg-gray-50 rounded-lg p-4 text-xs text-left max-w-lg mx-auto text-gray-600">from evalkit import EvalKitClient, Suite, TestCase

client = EvalKitClient()
client.log_trace(
    project_id={{ project.id }},
    test_case=TestCase(question="...", answer="...", context=["..."]),
    suite=Suite.RAG_QA,
    metadata={"model": "gpt-4o"},
)</pre>
</div>
{% endif %}
{% endblock %}
