{% extends 'base.html' %}
{% block title %}Analysis Runs - TLS Analyzer{% endblock %}
{% block content %}
<div class="card">
    <h2>All Analysis Runs</h2>

    <!-- Type filter -->
    <div style="margin-bottom:1em;">
        <form method="get" style="display:inline-flex;align-items:center;gap:0.5em;">
            <label for="type-filter">类型筛选:</label>
            <select name="type" id="type-filter" onchange="this.form.submit()">
                <option value="">全部</option>
                <option value="upload" {% if current_type == 'upload' %}selected{% endif %}>手动上传</option>
                <option value="manual" {% if current_type == 'manual' %}selected{% endif %}>手动分析</option>
                <option value="auto" {% if current_type == 'auto' %}selected{% endif %}>LLM自动</option>
            </select>
            {% if current_type %}
            <a href="{% url 'analysis:run_list' %}" style="font-size:0.9em;">清除筛选</a>
            {% endif %}
        </form>
    </div>

    {% if runs %}
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Started</th>
                <th>Status</th>
                <th>Type</th>
                <th>CSV Glob</th>
                <th>Entities</th>
                <th>Clusters</th>
                <th></th>
                <th>重试</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for run in runs %}
            <tr>
                <td>#{{ run.display_id }}</td>
                <td>{{ run.created_at|date:"Y-m-d H:i" }}</td>
                <td><span class="badge {% if run.status == 'completed' %}badge-success{% elif run.status == 'failed' %}badge-danger{% else %}badge-info{% endif %}">{{ run.get_status_display }}</span></td>
                <td style="max-width:300px;overflow:hidden;text-overflow:ellipsis;">{% if run.sqlite_table %}SQLite表 {{ run.sqlite_table }}{% else %}{{ run.csv_glob }}{% endif %}</td>
                <td>{{ run.entity_count|default:"-" }}</td>
                <td>{{ run.cluster_count|default:"-" }}</td>
                <td><a href="{% url 'analysis:run_detail' run.display_id %}" class="btn btn-primary">Detail</a></td>
                <td>
                    {% if run.status == 'failed' %}
                    <form method="post" action="{% url 'analysis:retry_run' run.display_id %}" style="display:inline;">
                        {% csrf_token %}
                        <button type="submit" style="background:#ffc107;color:#000;border:none;padding:2px 8px;font-size:0.85em;border-radius:3px;cursor:pointer;">重试</button>
                    </form>
                    {% endif %}
                </td>
                <td><button class="btn btn-danger" style="background:#dc3545;color:#fff;padding:0.25rem 0.5rem;font-size:0.8rem;" onclick="deleteRun({{ run.display_id }})">删除</button></td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="pagination">
        {% if page > 1 %}<a href="?page={{ page|add:-1 }}{% if current_type %}&type={{ current_type }}{% endif %}">← Prev</a>{% endif %}
        <span class="active">{{ page }}</span>
        {% if page < total_pages %}<a href="?page={{ page|add:1 }}{% if current_type %}&type={{ current_type }}{% endif %}">Next →</a>{% endif %}
    </div>
    {% else %}
    <div class="empty-state"><p>No runs yet.</p></div>
    {% endif %}
</div>

<div style="display:none;">{% csrf_token %}</div>

<script>
async function deleteRun(runId) {
    if (!confirm('确定要删除此运行记录吗？此操作不可撤销。')) return;
    try {
        const csrf = document.querySelector('[name=csrfmiddlewaretoken]');
        if (!csrf) { showError('页面已过期，请刷新后重试'); return; }
        const resp = await fetch('/runs/' + runId + '/delete/', {
            method: 'POST',
            headers: { 'X-CSRFToken': csrf.value },
        });
        if (!resp.ok) {
            const text = await resp.text().catch(() => '');
            showError('删除失败 (HTTP ' + resp.status + '): ' + (text.length > 200 ? text.substring(0, 200) + '…' : text || '服务器内部错误'));
            return;
        }
        const data = await resp.json();
        if (data.deleted) { showSuccess('已删除'); location.reload(); }
        else { showError('删除失败: 服务器返回了意外的响应'); }
    } catch (err) {
        showError('删除失败: ' + err.message + ' — 请刷新页面后重试');
    }
}
</script>
{% endblock %}
