{% extends 'base.html' %}
{% block title %}配置 - TLS Analyzer{% endblock %}
{% block content %}
<div class="card">
    <h2>系统配置</h2>
    <p style="color:#666;margin-bottom:1rem;">修改配置后点击「保存配置」持久化到 <code>config/config.yaml</code>。</p>
</div>

<form id="config-form" method="post">
    {% csrf_token %}

    {# ── Server ── #}
    <div class="card">
        <h2>服务器</h2>
        <div class="grid-3">
            <div class="form-group">
                <label for="server_host">Host</label>
                <input type="text" id="server_host" name="server_host" value="{{ config.server.host }}" class="form-input">
            </div>
            <div class="form-group">
                <label for="server_port">Port</label>
                <input type="number" id="server_port" name="server_port" value="{{ config.server.port }}" class="form-input">
            </div>
            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="server_debug" value="true" {% if config.server.debug %}checked{% endif %}>
                    Debug 模式
                </label>
            </div>
        </div>
        <p style="color:#856404;background:#fff3cd;padding:0.5rem 0.75rem;border-radius:4px;font-size:0.85rem;margin-top:0.5rem;">
            ⚠️ IP+Port 修改后需要重启服务才能生效
        </p>
    </div>

    {# ── Data ── #}
    <div class="card">
        <h2>数据</h2>
        <div class="grid-2">
            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="data_schema_strict" value="true" {% if config.data.schema_strict %}checked{% endif %}>
                    严格 Schema 校验
                </label>
            </div>
            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="data_recursive" value="true" {% if config.data.recursive %}checked{% endif %}>
                    递归扫描
                </label>
            </div>
        </div>
    </div>

    {# ── Clustering ── #}
    <div class="card">
        <h2>聚类</h2>
        <div class="grid-2">
            <div class="form-group">
                <label for="clustering_algorithm">算法</label>
                <select id="clustering_algorithm" name="clustering_algorithm" class="form-input">
                    <option value="hdbscan" {% if config.clustering.algorithm == 'hdbscan' %}selected{% endif %}>HDBSCAN</option>
                    <option value="kmeans" {% if config.clustering.algorithm == 'kmeans' %}selected{% endif %}>K-Means</option>
                    <option value="dbscan" {% if config.clustering.algorithm == 'dbscan' %}selected{% endif %}>DBSCAN</option>
                </select>
            </div>
            <div class="form-group">
                <label for="clustering_min_cluster_size">最小簇大小</label>
                <input type="number" id="clustering_min_cluster_size" name="clustering_min_cluster_size"
                       value="{{ config.clustering.min_cluster_size }}" min="2" class="form-input">
            </div>
        </div>
    </div>

    {# ── LLM ── #}
    <div class="card">
        <h2>LLM 连接</h2>
        <div class="form-group">
            <label class="checkbox-label">
                <input type="checkbox" name="llm_enabled" value="true" {% if config.llm.enabled %}checked{% endif %}>
                启用 LLM
            </label>
        </div>
        <div class="form-group">
            <label for="llm_base_url">Base URL</label>
            <input type="text" id="llm_base_url" name="llm_base_url" value="{{ config.llm.base_url }}"
                   placeholder="https://api.openai.com/v1" class="form-input">
        </div>
        <div class="form-group">
            <label for="llm_api_key">API Key</label>
            <input type="password" id="llm_api_key" name="llm_api_key" value="{{ config.llm.api_key }}"
                   placeholder="sk-..." class="form-input">
        </div>
        <div class="form-group">
            <label for="llm_model">Model</label>
            <input type="text" id="llm_model" name="llm_model" value="{{ config.llm.model }}"
                   placeholder="gpt-4" class="form-input">
        </div>

        {# LLM connectivity test button + result area #}
        <div style="margin-top:1rem; display:flex; align-items:center; gap:1rem; flex-wrap:wrap;">
            <button type="button" id="btn-llm-test" class="btn btn-primary" onclick="testLLM()">测试连通性</button>
            <span id="llm-test-result" style="font-size:0.9rem;"></span>
        </div>
    </div>

    {# ── Save button ── #}
    <div class="card" style="text-align:right;">
        <button type="submit" class="btn btn-primary" style="padding:0.6rem 2rem;">保存配置</button>
    </div>
</form>

{% if saved %}
<script>
    // Flash-style feedback: briefly highlight the message
    const el = document.createElement('div');
    el.style.cssText = 'position:fixed;top:1rem;right:1rem;background:#155724;color:#fff;padding:0.8rem 1.5rem;border-radius:6px;font-size:0.9rem;z-index:999;box-shadow:0 2px 8px rgba(0,0,0,0.2);';
    el.textContent = '✅ 配置已保存';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 3000);
</script>
{% endif %}

<script>
async function testLLM() {
    const btn = document.getElementById('btn-llm-test');
    const result = document.getElementById('llm-test-result');
    btn.disabled = true;
    btn.textContent = '测试中...';
    result.textContent = '';
    result.style.color = '';

    const payload = {
        base_url: document.getElementById('llm_base_url').value || '',
        api_key: document.getElementById('llm_api_key').value || '',
        model: document.getElementById('llm_model').value || '',
    };

    try {
        const resp = await fetch('/api/llm/test/', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCSRF() },
            body: JSON.stringify(payload),
        });
        const data = await resp.json();
        if (data.success) {
            result.style.color = '#155724';
            result.textContent = `✅ ${data.message} (${data.latency_ms}ms)`;
        } else {
            result.style.color = '#721c24';
            result.textContent = `❌ ${data.message}`;
        }
    } catch (err) {
        result.style.color = '#721c24';
        result.textContent = `❌ 请求失败: ${err.message}`;
        showError('LLM 连通性测试失败: ' + err.message);
    } finally {
        btn.disabled = false;
        btn.textContent = '测试连通性';
    }
}

function getCSRF() {
    return document.querySelector('[name=csrfmiddlewaretoken]')?.value || '';
}
</script>

<style>
.form-group { margin-bottom: 1rem; }
.form-group label { display: block; font-size: 0.85rem; color: #555; margin-bottom: 0.3rem; font-weight: 600; }
.form-input { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem; }
.form-input:focus { outline: none; border-color: #4361ee; box-shadow: 0 0 0 2px rgba(67,97,238,0.15); }
.checkbox-label { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; color: #333; cursor: pointer; }
.checkbox-label input[type="checkbox"] { width: 1rem; height: 1rem; cursor: pointer; }
.grid-2 .form-group, .grid-3 .form-group { min-width: 0; }
.card h2 { font-size: 1rem; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; margin-bottom: 1rem; }
</style>
{% endblock %}