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

{% block content %}
<style>
    .swal2-input::placeholder {
        opacity: 0.4;
    }
</style>

<div class="card card-row">
    <h1>Hello from ECDA LLM 👋</h1>
    <button id="continueBtn" class="btn" type="button">Continue</button>
</div>

<script>
    const continueBtn = document.getElementById("continueBtn");

    continueBtn.addEventListener("click", async () => {
        // Better: Local / External / Cancel (instead of using Cancel as External)
        const choice = await Swal.fire({
            title: "Select LLM source",
            text: "Do you want to use a local LLM or an external provider (e.g., OpenRouter)?",
            icon: "question",
            showCancelButton: true,
            showDenyButton: true,
            confirmButtonText: "Local LLM",
            denyButtonText: "External LLM",
            cancelButtonText: "Cancel",
        });

        if (choice.isConfirmed) {
            await startLocalFlow();
        } else if (choice.isDenied) {
            await startExternalFlow();
        }
    });

    async function startLocalFlow() {
        const defaults = {
            base_url: "http://localhost:1234/v1",
            api_key: "lm-studio",
        };

        const { value: cfg } = await Swal.fire({
            title: "Connect to your local LLM (LM Studio)",
            html: `
        <input id="swal-base" class="swal2-input" placeholder="Base URL" value="${defaults.base_url}">
        <input id="swal-key"  class="swal2-input" placeholder="API key (usually lm-studio)" value="${defaults.api_key}">
      `,
            showCancelButton: true,
            confirmButtonText: "Validate",
            cancelButtonText: "Cancel",
            focusConfirm: false,
            preConfirm: () => {
                const base_url = document.getElementById("swal-base").value.trim();
                const api_key = (document.getElementById("swal-key").value || "").trim() || "lm-studio";
                if (!base_url) Swal.showValidationMessage("Base URL is required");
                return { base_url, api_key };
            },
        });

        if (!cfg) return;

        await doValidate({
            provider: "local",
            base_url: cfg.base_url,
            api_key: cfg.api_key,
            model: null, // backend auto-picks from /models for local
        });
    }

    async function startExternalFlow() {
        // OpenRouter defaults (matches your working Python test)
        const defaults = {
            base_url: "https://openrouter.ai/api/v1",
            model: "openrouter/aurora-alpha",
        };

        const { value: cfg } = await Swal.fire({
            title: "Connect to external LLM (OpenRouter / OpenAI-compatible)",
            html: `
        <input id="swal-ext-base"  class="swal2-input" placeholder="Base URL" value="${defaults.base_url}">
        <input id="swal-ext-key"   class="swal2-input" placeholder="API key (sk-or-...)" type="password">
        <input id="swal-ext-model" class="swal2-input" placeholder="Model (e.g. openrouter/aurora-alpha)" value="${defaults.model}">
        <div style="font-size:12px;opacity:.8;margin-top:6px;">
          Your key is sent to your server for validation (recommended). It is not used directly in the browser.
        </div>
      `,
            showCancelButton: true,
            confirmButtonText: "Validate",
            cancelButtonText: "Cancel",
            focusConfirm: false,
            preConfirm: () => {
                const base_url = document.getElementById("swal-ext-base").value.trim();
                const api_key = document.getElementById("swal-ext-key").value.trim();
                const model = document.getElementById("swal-ext-model").value.trim();

                if (!base_url) Swal.showValidationMessage("Base URL is required");
                if (!api_key) Swal.showValidationMessage("API key is required");
                if (!model) Swal.showValidationMessage("Model is required");

                return { base_url, api_key, model };
            },
        });

        if (!cfg) return;

        await doValidate({
            provider: "external",
            base_url: cfg.base_url,
            api_key: cfg.api_key,
            model: cfg.model,
        });
    }

    async function doValidate({ provider, base_url, api_key, model }) {
        Swal.fire({
            title: "Checking…",
            text: "Verifying that the LLM is reachable and a chat completion works.",
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading(),
        });

        try {
            const res = await fetch("/api/validate", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    provider,
                    base_url,
                    api_key,
                    model, // null OK for local
                    test_prompt: "ping",
                }),
            });

            let data;
            try {
                data = await res.json();
            } catch {
                data = { ok: false, message: await res.text() };
            }

            if (!data.ok) {
                await Swal.fire({
                    icon: "error",
                    title: "Validation failed",
                    text: data.message || "Unknown error",
                });
                return;
            }

            const finalModel = data.chat_model || model || "";

            // Save to SERVER so Settings page can load it later
            await fetch("/api/settings", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    provider,
                    base_url,
                    api_key,
                    model: finalModel,                // store resolved model
                    embed_model: "nomic-embed-text-v1.5",
                }),
            });

            // Save config
            sessionStorage.setItem("LLM_PROVIDER", provider);
            sessionStorage.setItem("LLM_BASE_URL", base_url);
            sessionStorage.setItem("LLM_API_KEY", api_key);
            if (finalModel) sessionStorage.setItem("LLM_MODEL", finalModel);

            // Embeddings stay LOCAL via FastEmbed
            sessionStorage.setItem("EMBED_MODEL", "nomic-embed-text-v1.5");

            await Swal.fire({
                icon: "success",
                title: "Connected!",
                text: `Provider: ${provider}\nChat: ${finalModel}\nEmbeddings: nomic-embed-text-v1.5 (local)`,
                timer: 1400,
                showConfirmButton: false,
            });

            window.location.href = "/upload";
        } catch (err) {
            await Swal.fire({
                icon: "error",
                title: "Network error",
                text: String(err),
            });
        }
    }
</script>
{% endblock %}