{% extends "base.html" %}

{% block title %}{{ provider.name }} - 详情 - AgomTradePro{% endblock %}

{% block content %}
<a href="{% if provider.scope == 'user' %}{% url 'ai_provider:my-providers' %}{% else %}{% url 'ai_provider:manage' %}{% endif %}" style="display: inline-block; margin-bottom: 12px; color: var(--text-secondary, #6c757d); text-decoration: none; font-size: 14px;">&larr; 返回{% if provider.scope == 'user' %}我的 Provider{% else %} AI 管理{% endif %}</a>
<div class="page-header">
    <h1>{{ provider.name }}</h1>
    <p class="subtitle">{{ provider.provider_type_label }} - {{ provider.description }}</p>
</div>

<!-- 基本信息 -->
<div class="section">
    <h2 class="section-title">基本信息</h2>
    <div class="card">
        <table style="width: 100%; border-collapse: collapse;">
            <tr>
                <td style="padding: 8px; width: 150px;"><strong>名称:</strong></td>
                <td style="padding: 8px;">{{ provider.name }}</td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>类型:</strong></td>
                <td style="padding: 8px;">{{ provider.provider_type_label }}</td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>状态:</strong></td>
                <td style="padding: 8px;">
                    {% if provider.is_active %}
                        <span class="tag tag-success">启用</span>
                    {% else %}
                        <span class="tag tag-error">禁用</span>
                    {% endif %}
                </td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>归属范围:</strong></td>
                <td style="padding: 8px;">
                    {% if provider.scope == 'user' %}
                        个人 Provider
                    {% else %}
                        系统 Provider
                    {% endif %}
                </td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>优先级:</strong></td>
                <td style="padding: 8px;">{{ provider.priority }}</td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>Base URL:</strong></td>
                <td style="padding: 8px;"><code>{{ provider.base_url }}</code></td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>默认模型:</strong></td>
                <td style="padding: 8px;"><code>{{ provider.default_model }}</code></td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>每日预算:</strong></td>
                <td style="padding: 8px;">{% if provider.daily_budget_limit %}${{ provider.daily_budget_limit }}{% else %}无限制{% endif %}</td>
            </tr>
            <tr>
                <td style="padding: 8px;"><strong>每月预算:</strong></td>
                <td style="padding: 8px;">{% if provider.monthly_budget_limit %}${{ provider.monthly_budget_limit }}{% else %}无限制{% endif %}</td>
            </tr>
        </table>
        <div style="margin-top: 16px;">
            <a href="{% url 'ai_provider:edit' provider.id %}" class="tag">编辑配置</a>
            <a href="{% url 'settings-center' %}" class="tag">进入设置中心</a>
            <a href="{% if provider.scope == 'user' %}{% url 'ai_provider:my-providers' %}{% else %}{% url 'ai_provider:manage' %}{% endif %}" class="tag">返回列表</a>
            {% if provider.scope == 'system' %}
            <button id="btn-test-connection" class="tag" onclick="testConnection()" style="cursor: pointer; border: none; background: var(--color-warning, #f0ad4e); color: #fff;">测试连接</button>
            {% endif %}
        </div>

        <!-- 测试结果 -->
        {% if provider.scope == 'system' %}
        <div id="test-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 4px;"></div>
        {% endif %}
    </div>
</div>

<!-- 统计信息 -->
<div class="section">
    <h2 class="section-title">使用统计</h2>

    <!-- 今日统计 -->
    <div class="card" style="margin-bottom: 16px;">
        <h3 style="margin-bottom: 12px;">今日</h3>
        <div class="status-grid">
            <div>
                <div class="status-label">请求数</div>
                <div class="status-value">{{ today_usage.total_requests }}</div>
            </div>
            <div>
                <div class="status-label">成功</div>
                <div class="status-value" style="color: var(--color-success);">{{ today_usage.success_requests }}</div>
            </div>
            <div>
                <div class="status-label">Tokens</div>
                <div class="status-value">{{ today_usage.total_tokens }}</div>
            </div>
            <div>
                <div class="status-label">成本</div>
                <div class="status-value">${{ today_usage.total_cost|floatformat:4 }}</div>
            </div>
        </div>
    </div>

    <!-- 本月统计 -->
    <div class="card">
        <h3 style="margin-bottom: 12px;">本月</h3>
        <div class="status-grid">
            <div>
                <div class="status-label">请求数</div>
                <div class="status-value">{{ month_usage.total_requests }}</div>
            </div>
            <div>
                <div class="status-label">成功</div>
                <div class="status-value" style="color: var(--color-success);">{{ month_usage.success_requests }}</div>
            </div>
            <div>
                <div class="status-label">Tokens</div>
                <div class="status-value">{{ month_usage.total_tokens }}</div>
            </div>
            <div>
                <div class="status-label">成本</div>
                <div class="status-value">${{ month_usage.total_cost|floatformat:2 }}</div>
            </div>
        </div>
    </div>
</div>

<!-- 模型统计 -->
{% if model_stats %}
<div class="section">
    <h2 class="section-title">按模型统计（最近30天）</h2>
    <div class="card">
        <table style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr style="border-bottom: 2px solid var(--color-border);">
                    <th style="padding: 8px; text-align: left;">模型</th>
                    <th style="padding: 8px; text-align: right;">请求数</th>
                    <th style="padding: 8px; text-align: right;">Tokens</th>
                    <th style="padding: 8px; text-align: right;">成本</th>
                    <th style="padding: 8px; text-align: right;">平均耗时</th>
                </tr>
            </thead>
            <tbody>
                {% for stat in model_stats %}
                <tr style="border-bottom: 1px solid var(--color-border-light);">
                    <td style="padding: 8px;"><code>{{ stat.model }}</code></td>
                    <td style="padding: 8px; text-align: right;">{{ stat.requests }}</td>
                    <td style="padding: 8px; text-align: right;">{{ stat.tokens }}</td>
                    <td style="padding: 8px; text-align: right;">${{ stat.cost|floatformat:4 }}</td>
                    <td style="padding: 8px; text-align: right;">{{ stat.avg_response_time|floatformat:0 }}ms</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}

<!-- 最近日志 -->
{% if recent_logs %}
<div class="section">
    <h2 class="section-title">最近调用</h2>
    <div style="margin-bottom: 16px;">
        <a href="{% url 'ai_provider:logs' %}?provider={{ provider.id }}" class="tag">查看全部日志</a>
    </div>
    <table style="width: 100%; border-collapse: collapse;">
        <thead>
            <tr style="border-bottom: 2px solid var(--color-border);">
                <th style="padding: 8px; text-align: left;">时间</th>
                <th style="padding: 8px; text-align: left;">归因</th>
                <th style="padding: 8px; text-align: left;">模型</th>
                <th style="padding: 8px; text-align: right;">Tokens</th>
                <th style="padding: 8px; text-align: right;">成本</th>
                <th style="padding: 8px; text-align: center;">兜底计费</th>
                <th style="padding: 8px; text-align: right;">耗时</th>
                <th style="padding: 8px; text-align: center;">状态</th>
            </tr>
        </thead>
        <tbody>
            {% for log in recent_logs %}
            <tr style="border-bottom: 1px solid var(--color-border-light);">
                <td style="padding: 8px;">{{ log.created_at|date:"m-d H:i:s" }}</td>
                <td style="padding: 8px;">
                    {% if log.provider_scope == 'personal' %}
                        <span class="tag">个人 Provider</span>
                    {% elif log.provider_scope == 'system_fallback' %}
                        <span class="tag" style="background: #fef3c7; color: #92400e;">系统兜底</span>
                    {% else %}
                        <span class="tag" style="background: #dbeafe; color: #1d4ed8;">系统全局</span>
                    {% endif %}
                </td>
                <td style="padding: 8px;"><code>{{ log.model }}</code></td>
                <td style="padding: 8px; text-align: right;">{{ log.total_tokens }}</td>
                <td style="padding: 8px; text-align: right;">${{ log.estimated_cost|floatformat:6 }}</td>
                <td style="padding: 8px; text-align: center;">
                    {% if log.quota_charged %}
                        <span class="tag" style="background: #fee2e2; color: #b91c1c;">是</span>
                    {% else %}
                        <span class="tag">否</span>
                    {% endif %}
                </td>
                <td style="padding: 8px; text-align: right;">{{ log.response_time_ms }}ms</td>
                <td style="padding: 8px; text-align: center;">
                    {% if log.status == 'success' %}
                        <span class="tag tag-success">成功</span>
                    {% else %}
                        <span class="tag tag-error">失败</span>
                    {% endif %}
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% endif %}

{% endblock %}

{% block extra_js %}
{% if provider.scope == 'system' %}
<script>
function testConnection() {
    const btn = document.getElementById('btn-test-connection');
    const resultDiv = document.getElementById('test-result');

    btn.disabled = true;
    btn.textContent = '测试中...';
    resultDiv.style.display = 'block';
    resultDiv.style.background = 'var(--color-bg-secondary, #f5f5f5)';
    resultDiv.innerHTML = '<span>正在连接 AI 提供商，请稍候...</span>';

    fetch('/api/ai/providers/{{ provider.id }}/test-connection/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken(),
        },
    })
    .then(response => response.json())
    .then(data => {
        btn.disabled = false;
        btn.textContent = '测试连接';

        if (data.status === 'success') {
            resultDiv.style.background = 'rgba(40, 167, 69, 0.1)';
            resultDiv.style.border = '1px solid var(--color-success, #28a745)';
            resultDiv.innerHTML =
                '<strong style="color: var(--color-success, #28a745);">连接成功</strong>' +
                '<p style="margin: 8px 0 0;">Provider: <code>' + escapeHtml(data.provider || '{{ provider.name }}') + '</code></p>' +
                '<p style="margin: 4px 0 0;">' + escapeHtml(data.message || 'Provider health check passed') + '</p>';
        } else {
            resultDiv.style.background = 'rgba(220, 53, 69, 0.1)';
            resultDiv.style.border = '1px solid var(--color-error, #dc3545)';
            resultDiv.innerHTML =
                '<strong style="color: var(--color-error, #dc3545);">连接失败</strong>' +
                '<p style="margin: 8px 0 0; word-break: break-all;">' + escapeHtml(data.error_message || data.error || '未知错误') + '</p>' +
                (data.response_time_ms ? '<p style="margin: 4px 0 0;">耗时: ' + data.response_time_ms + 'ms</p>' : '');
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.textContent = '测试连接';
        resultDiv.style.background = 'rgba(220, 53, 69, 0.1)';
        resultDiv.style.border = '1px solid var(--color-error, #dc3545)';
        resultDiv.innerHTML = '<strong style="color: var(--color-error, #dc3545);">请求失败</strong><p style="margin: 8px 0 0;">' + escapeHtml(err.message) + '</p>';
    });
}

function getCsrfToken() {
    const cookie = document.cookie.split(';').find(c => c.trim().startsWith('csrftoken='));
    return cookie ? cookie.split('=')[1] : '';
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
</script>
{% endif %}
{% endblock %}
