{% extends "base.html" %}
{% block title %}Settings | ECDA LLM{% endblock %}

{% block content %}
<div class="card card-col upload-card">
    <div class="chat-header">
        <h2>Settings</h2>
        <div class="tooltip-container">
            <a class="btn btn-ghost" href="/">Home</a>
            <span class="tooltip">Back to Home</span>
        </div>
    </div>

    <div class="settings-form">
        <div class="field">
            <div class="field-label">Provider</div>
            <select id="provider" class="control">
                <option value="local">Local (LM Studio)</option>
                <option value="external">External (OpenRouter/OpenAI-compatible)</option>
            </select>
        </div>

        <div class="field">
            <div class="field-label">Base URL</div>
            <input id="base_url" class="control" placeholder="http://localhost:1234/v1" readonly />
        </div>

        <div class="field">
            <div class="field-label">Model</div>
            <input id="model" class="control" placeholder="openrouter/aurora-alpha" readonly />
        </div>

        <div class="field" id="apiKeyField">
            <div class="field-label">API Key</div>
            <input id="api_key" class="control" type="password" placeholder="(stored on server)" readonly />
            <div id="keyHint" class="field-hint"></div>
        </div>

        <div class="field">
            <div class="field-label">Embedding model (local)</div>
            <input id="embed_model" class="control" readonly />
        </div>

        <div class="settings-actions">
            <!-- Save button removed -->
            <a class="btn btn-ghost" href="/upload">Upload</a>

            <button id="testBtn" class="btn btn-ghost" type="button">Test (Validate)</button>
            <div id="status" class="status"></div>
        </div>
    </div>
</div>

<script>


    function updateProviderUI(provider) {
        const apiKeyField = el("apiKeyField");

        if (provider === "local") {
            apiKeyField.style.display = "none";
        } else {
            apiKeyField.style.display = "block";
        }
    }


    const el = (id) => document.getElementById(id);


    el("provider").addEventListener("change", (e) => {
        updateProviderUI(e.target.value);
    });

    async function loadSettings() {
        el("status").textContent = "Loading…";
        try {
            const res = await fetch("/api/settings");
            const data = await res.json();

            if (!data.ok) {
                el("status").textContent = "Could not load settings";
                return;
            }

            el("provider").value = data.provider || "local";
            updateProviderUI(el("provider").value);
            el("base_url").value = data.base_url || "";
            el("model").value = data.model || "";
            el("embed_model").value = data.embed_model || "nomic-embed-text-v1.5";

            // ✅ ADD THIS: restore config into sessionStorage for pages that depend on it
            sessionStorage.setItem("LLM_BASE_URL", data.base_url || "");
            sessionStorage.setItem("LLM_MODEL", data.model || "");
            sessionStorage.setItem("EMBED_MODEL", data.embed_model || "nomic-embed-text-v1.5");
            // NOTE: don't store API key in sessionStorage (you intentionally keep it server-side)

            // never show key; only hint
            el("keyHint").textContent = data.has_api_key
                ? "API key is saved securely on the server."
                : "No API key saved yet (configure from Home).";

            el("status").textContent = "";
        } catch (e) {
            el("status").textContent = "❌ Network error: " + String(e);
        }
    }

    async function testValidate() {
        el("status").textContent = "Validating saved settings…";
        el("testBtn").disabled = true;

        try {
            const res = await fetch("/api/validate_saved", { method: "POST" });
            const data = await res.json();

            if (!data.ok) {
                el("status").textContent = "❌ " + (data.message || "Validation failed");
                return;
            }

            el("status").textContent = "✅ Connected — " + (data.chat_model || "");
        } catch (e) {
            el("status").textContent = "❌ Network error: " + String(e);
        } finally {
            el("testBtn").disabled = false;
        }
    }

    el("testBtn").addEventListener("click", testValidate);
    loadSettings();


</script>

{% endblock %}