{% extends "base.html" %}
{% block title %}Evaluation #{{ evaluation.id }} — evalkit{% endblock %}
{% block content %}
<div class="mb-6">
    <p class="text-sm text-gray-400 mb-1">
        <a href="/" class="hover:underline">Projects</a> /
        <a href="/projects/{{ evaluation.project_id }}" class="hover:underline">Project #{{ evaluation.project_id }}</a> /
        Evaluation #{{ evaluation.id }}
    </p>
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-semibold">Evaluation #{{ evaluation.id }}</h1>
        <a href="/evaluations/{{ evaluation.id }}/report"
            class="text-sm text-indigo-600 border border-indigo-200 px-4 py-2 rounded-lg hover:bg-indigo-50">
            Download JSON
        </a>
    </div>
</div>

<!-- Overview cards -->
<div class="grid gap-4 sm:grid-cols-4 mb-8">
    <div class="bg-white rounded-xl border border-gray-200 p-4">
        <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Suite</p>
        <p class="font-semibold">{{ evaluation.suite_name }}</p>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4">
        <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Status</p>
        <span class="inline-block px-2 py-0.5 rounded-full text-xs font-semibold
            {% if evaluation.status.value == 'complete' %}bg-green-100 text-green-800
            {% elif evaluation.status.value == 'running' %}bg-blue-100 text-blue-800
            {% elif evaluation.status.value == 'failed' %}bg-red-100 text-red-800
            {% else %}bg-gray-100 text-gray-600{% endif %}">
            {{ evaluation.status.value }}
        </span>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4">
        <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Average Score</p>
        {% if evaluation.average_score is not none %}
            {% set pct = (evaluation.average_score * 100) | int %}
            <p class="font-semibold text-xl {% if pct >= 80 %}text-green-600{% elif pct >= 50 %}text-yellow-600{% else %}text-red-600{% endif %}">
                {{ pct }}%
            </p>
        {% else %}
            <p class="text-gray-400">—</p>
        {% endif %}
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-4">
        <p class="text-xs text-gray-400 uppercase tracking-wide mb-1">Test Cases</p>
        <p class="font-semibold text-xl">{{ evaluation.results | length }}</p>
    </div>
</div>

<!-- Tags -->
{% set tag_dict = {} %}
{% for t in evaluation.tags %}{% set _ = tag_dict.update({t.key: t.value}) %}{% endfor %}
<div class="mb-6" x-data="{ editing: false }">
    <div class="flex items-center gap-3 mb-2">
        <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Tags</h3>
        <button @click="editing = !editing" class="text-xs text-indigo-600 hover:underline" x-text="editing ? 'Cancel' : 'Edit tags'"></button>
    </div>

    <!-- Tag display -->
    <div x-show="!editing" id="tag-display">
        {% if tag_dict %}
        <div class="flex flex-wrap gap-2">
            {% for key, value in tag_dict.items() %}
            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                <span class="text-gray-400">{{ key }}:</span> {{ value }}
            </span>
            {% endfor %}
        </div>
        {% else %}
        <p class="text-xs text-gray-400">No tags</p>
        {% endif %}
    </div>

    <!-- Tag edit form (Alpine.js + fetch) -->
    <div x-show="editing" x-cloak
         x-data="{ rows: [{% for key, value in tag_dict.items() %}{ key: {{ key | tojson }}, value: {{ value | tojson }} },{% endfor %}], originalKeys: [{% for key in tag_dict.keys() %}{{ key | tojson }},{% endfor %}], saving: false }"
         x-init="if (rows.length === 0) rows.push({ key: '', value: '' })">
        <div class="space-y-2 max-w-md">
            <template x-for="(row, i) in rows" :key="i">
                <div class="flex gap-2">
                    <input x-model="row.key" class="border rounded px-2 py-1 text-xs w-1/3" placeholder="key">
                    <input x-model="row.value" class="border rounded px-2 py-1 text-xs w-1/2" placeholder="value">
                    <button type="button" @click="rows.splice(i, 1)" class="text-red-400 hover:text-red-600 text-xs">Remove</button>
                </div>
            </template>
            <div class="flex gap-2 pt-1">
                <button type="button" @click="rows.push({ key: '', value: '' })"
                        class="text-xs text-indigo-600 hover:underline">+ Add tag</button>
                <button type="button" :disabled="saving"
                        @click="
                            saving = true;
                            const tags = {};
                            rows.filter(r => r.key.trim()).forEach(r => tags[r.key] = r.value);
                            originalKeys.forEach(k => { if (!(k in tags)) tags[k] = null; });
                            fetch('/api/v1/evaluations/{{ evaluation.id }}/tags', {
                                method: 'PUT',
                                headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({tags})
                            })
                            .then(r => r.json())
                            .then(() => location.reload())
                            .finally(() => saving = false);
                        "
                        class="text-xs bg-indigo-600 text-white px-3 py-1 rounded hover:bg-indigo-700">Save</button>
            </div>
        </div>
    </div>
</div>

<!-- Compare with previous -->
{% if prev_evaluation %}
<div class="mb-6">
    <a href="/projects/{{ evaluation.project_id }}/compare?ids={{ prev_evaluation.id }},{{ evaluation.id }}&baseline={{ prev_evaluation.id }}"
       class="text-sm text-indigo-600 border border-indigo-200 px-4 py-2 rounded-lg hover:bg-indigo-50 inline-block">
        Compare with previous (#{{ prev_evaluation.id }})
    </a>
</div>
{% endif %}

{% if evaluation.results %}
<!-- Per-metric summary -->
{% set metric_names = [] %}
{% for r in evaluation.results %}
  {% for ms in r.metric_scores %}
    {% if ms.metric_name not in metric_names %}{% set _ = metric_names.append(ms.metric_name) %}{% endif %}
  {% endfor %}
{% endfor %}

{% if metric_names %}
<div class="bg-white rounded-xl border border-gray-200 p-5 mb-6">
    <h2 class="text-sm font-semibold text-gray-600 mb-4">Metric Breakdown</h2>
    <div class="space-y-3">
        {% for mn in metric_names %}
            {% set scores = [] %}
            {% set passed = [] %}
            {% for r in evaluation.results %}
                {% for ms in r.metric_scores %}
                    {% if ms.metric_name == mn %}
                        {% set _ = scores.append(ms.score) %}
                        {% if ms.passed %}{% set _ = passed.append(1) %}{% endif %}
                    {% endif %}
                {% endfor %}
            {% endfor %}
            {% set avg = (scores | sum / scores | length) if scores else 0 %}
            {% set pct = (avg * 100) | int %}
            <div>
                <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-medium">{{ mn }}</span>
                    <span class="text-xs text-gray-500">{{ passed | length }}/{{ scores | length }} passed &bull; avg {{ pct }}%</span>
                </div>
                <div class="h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div class="h-full rounded-full {% if pct >= 80 %}bg-green-500{% elif pct >= 50 %}bg-yellow-400{% else %}bg-red-400{% endif %}"
                         style="width: {{ pct }}%"></div>
                </div>
            </div>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Results table -->
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <h2 class="text-sm font-semibold text-gray-600 px-5 py-3 border-b border-gray-100">Test Cases</h2>
    <div class="divide-y divide-gray-100">
        {% for result in evaluation.results %}
        {% set tc = result.get_test_case_dict() %}
        <details class="group">
            <summary class="flex items-center justify-between px-5 py-3 cursor-pointer hover:bg-gray-50 list-none">
                <div class="flex items-center gap-3 min-w-0">
                    <span class="shrink-0 w-6 h-6 rounded-full text-xs flex items-center justify-center font-semibold
                        {% set pct = (result.overall_score * 100) | int %}
                        {% if pct >= 80 %}bg-green-100 text-green-700
                        {% elif pct >= 50 %}bg-yellow-100 text-yellow-700
                        {% else %}bg-red-100 text-red-700{% endif %}">
                        {{ pct }}
                    </span>
                    <p class="text-sm truncate text-gray-700">{{ tc.question }}</p>
                </div>
                <div class="flex gap-2 shrink-0 ml-4">
                    {% for ms in result.metric_scores %}
                    <span class="text-xs px-1.5 py-0.5 rounded {% if ms.passed %}bg-green-100 text-green-700{% else %}bg-red-100 text-red-700{% endif %}">
                        {{ ms.metric_name | replace('_metric', '') | replace('_', ' ') | truncate(8, True, '') }}
                    </span>
                    {% endfor %}
                </div>
            </summary>
            <div class="px-5 pb-4 pt-2 bg-gray-50 text-sm space-y-2">
                {% if tc.answer %}
                <div><span class="font-medium">Answer:</span> {{ tc.answer }}</div>
                {% endif %}
                {% if tc.context %}
                <div><span class="font-medium">Context:</span>
                    <ul class="list-disc ml-4 mt-1 space-y-0.5">
                        {% for chunk in tc.context %}<li class="text-gray-600">{{ chunk }}</li>{% endfor %}
                    </ul>
                </div>
                {% endif %}
                {% if tc.expected_answer %}
                <div><span class="font-medium">Expected:</span> {{ tc.expected_answer }}</div>
                {% endif %}
                {% if tc.expected_tool_calls or tc.actual_tool_calls %}
                <div class="mt-2">
                    <span class="font-medium">Tool Calls:</span>
                    <div class="grid grid-cols-2 gap-4 mt-1">
                        <div>
                            <p class="text-xs text-gray-500 font-medium mb-1">Expected</p>
                            {% for tool in (tc.expected_tool_calls or []) %}
                            <div class="mb-1 px-2 py-1 rounded bg-white border border-gray-200">
                                <span class="font-mono text-xs font-semibold">{{ tool.name }}</span>
                                {% if tool.parameters %}
                                <pre class="text-xs text-gray-500 mt-0.5">{{ tool.parameters | tojson(indent=2) }}</pre>
                                {% endif %}
                            </div>
                            {% endfor %}
                        </div>
                        <div>
                            <p class="text-xs text-gray-500 font-medium mb-1">Actual</p>
                            {% for tool in (tc.actual_tool_calls or []) %}
                            {% set idx = loop.index0 %}
                            {% set expected_list = tc.expected_tool_calls or [] %}
                            {% set name_match = idx < expected_list | length and expected_list[idx].name == tool.name %}
                            <div class="mb-1 px-2 py-1 rounded border {% if name_match %}bg-green-50 border-green-200{% else %}bg-red-50 border-red-200{% endif %}">
                                <span class="font-mono text-xs font-semibold">{{ tool.name }}</span>
                                {% if tool.parameters %}
                                <pre class="text-xs text-gray-500 mt-0.5">{{ tool.parameters | tojson(indent=2) }}</pre>
                                {% endif %}
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>
                {% endif %}
                <div class="mt-2 space-y-1">
                    {% for ms in result.metric_scores %}
                    <div class="flex gap-3 items-start">
                        <span class="text-xs px-1.5 py-0.5 rounded shrink-0 {% if ms.passed %}bg-green-100 text-green-700{% else %}bg-red-100 text-red-700{% endif %}">
                            {{ "%.2f"|format(ms.score) }}
                        </span>
                        <span class="text-xs text-gray-500"><span class="font-medium text-gray-700">{{ ms.metric_name }}:</span> {{ ms.reason }}</span>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </details>
        {% endfor %}
    </div>
</div>
{% else %}
<div class="text-center py-12 text-gray-400 bg-white rounded-xl border border-gray-200">
    {% if evaluation.status.value == 'pending' or evaluation.status.value == 'running' %}
    <p class="text-3xl mb-3">⏳</p>
    <p class="font-medium">Evaluation in progress</p>
    <p class="text-sm mt-1">Results will appear here once complete.</p>
    {% else %}
    <p class="text-3xl mb-3">📭</p>
    <p class="font-medium">No results available</p>
    {% endif %}
</div>
{% endif %}
{% endblock %}
