{% extends "base.html" %}
{% block content %}
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h1 class="h3 mb-0">{{ page_title }}</h1>
        <div class="d-flex gap-2">
            <input type="text" class="form-control" id="mcp-client-id" placeholder="按 Token 过滤">
            <button class="btn btn-outline-secondary" onclick="loadTraces(1)">刷新</button>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            <div id="trace-list"></div>
            <nav id="pagination" class="mt-3"><ul class="pagination mb-0"></ul></nav>
        </div>
    </div>
</div>

<div class="modal fade" id="trace-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">决策链详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body" id="trace-detail-content"></div>
        </div>
    </div>
</div>

<script>
var currentPage = 1;
var pageSize = 20;

function escapeHtml(value) {
    if (value === null || value === undefined) return '';
    return String(value)
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;');
}

function formatTime(value) {
    return value ? new Date(value).toLocaleString('zh-CN') : '-';
}

function loadTraces(page) {
    currentPage = page || 1;
    var token = $('#mcp-client-id').val();
    var params = 'page=' + currentPage + '&page_size=' + pageSize;
    if (token) {
        params += '&mcp_client_id=' + encodeURIComponent(token);
    }
    $.get('/api/audit/decision-traces/?' + params, function(data) {
        renderTraceList(data.traces || []);
        renderPagination(data.total_count || 0);
    });
}

function renderTraceList(traces) {
    if (!traces.length) {
        $('#trace-list').html('<div class="text-muted">暂无决策链记录</div>');
        return;
    }

    var html = '<div class="table-responsive"><table class="table table-hover align-middle">';
    html += '<thead><tr><th>请求ID</th><th>开始时间</th><th>步骤数</th><th>Token</th><th>工具链</th><th>摘要</th><th>状态</th><th></th></tr></thead><tbody>';
    traces.forEach(function(trace) {
        html += `
            <tr>
                <td><code>${escapeHtml(trace.request_id)}</code></td>
                <td>${formatTime(trace.started_at)}</td>
                <td>${trace.step_count}</td>
                <td><code>${escapeHtml(trace.mcp_client_id || '-')}</code></td>
                <td><small>${escapeHtml((trace.tools || []).join(' -> '))}</small></td>
                <td>${escapeHtml(trace.summary || '-')}</td>
                <td><span class="badge bg-${trace.status === 'failed' ? 'danger' : 'success'}">${escapeHtml(trace.status)}</span></td>
                <td><button class="btn btn-sm btn-outline-primary" onclick="showTraceDetail('${encodeURIComponent(trace.request_id)}', '${encodeURIComponent(trace.mcp_client_id || '')}')">查看</button></td>
            </tr>
        `;
    });
    html += '</tbody></table></div>';
    $('#trace-list').html(html);
}

function renderPagination(totalCount) {
    var totalPages = Math.ceil(totalCount / pageSize);
    if (totalPages <= 1) {
        $('#pagination ul').html('');
        return;
    }

    var html = '';
    if (currentPage > 1) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadTraces(${currentPage - 1}); return false;">上一页</a></li>`;
    }
    html += `<li class="page-item disabled"><span class="page-link">${currentPage} / ${totalPages}</span></li>`;
    if (currentPage < totalPages) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadTraces(${currentPage + 1}); return false;">下一页</a></li>`;
    }
    $('#pagination ul').html(html);
}

function showTraceDetail(requestId, clientId) {
    var url = '/api/audit/decision-traces/' + requestId + '/';
    if (clientId) {
        url += '?mcp_client_id=' + clientId;
    }
    $.get(url, function(data) {
        if (!data.success) {
            alert(data.error || '加载失败');
            return;
        }

        var trace = data.trace;
        var html = `
            <div class="mb-3">
                <div><strong>请求ID:</strong> <code>${escapeHtml(trace.request_id)}</code></div>
                <div><strong>Token:</strong> <code>${escapeHtml(trace.mcp_client_id || '-')}</code></div>
                <div><strong>时间范围:</strong> ${formatTime(trace.started_at)} - ${formatTime(trace.finished_at)}</div>
                <div><strong>最终结论:</strong> ${escapeHtml(trace.final_summary || '-')}</div>
            </div>
        `;

        html += '<div class="list-group">';
        (trace.steps || []).forEach(function(step) {
            html += `
                <div class="list-group-item">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div><strong>Step ${step.step_index}.</strong> <code>${escapeHtml(step.tool_name)}</code></div>
                        <span class="badge bg-${step.response_status >= 400 ? 'danger' : 'success'}">${step.response_status}</span>
                    </div>
                    <div class="small text-muted mb-2">${formatTime(step.timestamp)} | ${escapeHtml(step.module)} | ${escapeHtml(step.action)} | ${step.duration_ms || '-'} ms</div>
                    <div class="mb-2">${escapeHtml(step.summary || '-')}</div>
                </div>
            `;
        });
        html += '</div>';

        if (trace.logs && trace.logs.length) {
            html += '<hr><h6>详细日志</h6>';
            trace.logs.forEach(function(log, idx) {
                var payloadText = log.response_payload !== null && log.response_payload !== undefined
                    ? JSON.stringify(log.response_payload, null, 2)
                    : (log.response_text || '');
                html += `
                    <div class="card mb-3">
                        <div class="card-header">Log ${idx + 1}: <code>${escapeHtml(log.mcp_tool_name || '-') }</code></div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6"><strong>请求路径</strong><pre class="bg-light p-2">${escapeHtml(log.request_path || '-')}</pre></div>
                                <div class="col-md-6"><strong>请求参数</strong><pre class="bg-light p-2">${escapeHtml(JSON.stringify(log.request_params || {}, null, 2))}</pre></div>
                                <div class="col-12"><strong>响应内容</strong><pre class="bg-light p-2">${escapeHtml(payloadText || '-')}</pre></div>
                                ${log.exception_traceback ? `<div class="col-12"><strong>异常堆栈</strong><pre class="bg-light p-2">${escapeHtml(log.exception_traceback)}</pre></div>` : ''}
                            </div>
                        </div>
                    </div>
                `;
            });
        }

        $('#trace-detail-content').html(html);
        var modal = new bootstrap.Modal(document.getElementById('trace-modal'));
        modal.show();
    });
}

$(function() {
    $('#mcp-client-id').on('change', function() {
        loadTraces(1);
    });
    loadTraces(1);
});
</script>
{% endblock %}
