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

{% block content %}
<div class="card card-col chat-container">
    <div class="chat-header">
        <h2>Chat about Documents</h2>
        <div>

            <div class="tooltip-container">
                <a class="btn btn-ghost" href="/upload">Upload</a>
                <span class="tooltip">Upload more?</span>
            </div>
            <div class="tooltip-container">
                <a class="btn btn-ghost" href="/">Home</a>
                <span class="tooltip">Back to home</span>
            </div>

            <div class="tooltip-container">
                <button id="resetBtn" class="btn btn-ghost" type="button">Delete</button>
                <span class="tooltip">Delete all of files</span>
            </div>
            <div class="tooltip-container">
                <button id="saveBtn" class="btn btn-ghost" type="button">Save</button>
                <span class="tooltip">Save all chat in PDF</span>
            </div>


        </div>

    </div>


    <div class="meta" id="meta"></div>
    <div id="filesMeta" class="files-meta"></div>

    <div id="messages" class="messages" aria-live="polite"></div>

    <form id="chatForm" class="chat-form">
        <input id="messageInput" class="input" type="text" placeholder="Type a message…" autocomplete="off" />
        <button class="btn" type="submit">Send</button>
    </form>
</div>

<script>
    const baseUrl = sessionStorage.getItem("LLM_BASE_URL");
    const apiKey = sessionStorage.getItem("LLM_API_KEY") || "lm-studio";
    const model = sessionStorage.getItem("LLM_MODEL");
    const embedModel = sessionStorage.getItem("EMBED_MODEL") || "nomic-embed-text-v1.5";

    if (!baseUrl || !model) window.location.href = "/";

    const metaEl = document.getElementById("meta");
    if (metaEl) metaEl.textContent = `Chat: ${model} @ ${baseUrl} | Embeddings: ${embedModel} (local)`;

    const messagesEl = document.getElementById("messages");
    const form = document.getElementById("chatForm");
    const input = document.getElementById("messageInput");
    const sendBtn = form.querySelector("button[type='submit']");
    const resetBtn = document.getElementById("resetBtn");
    const saveBtn = document.getElementById("saveBtn");

    function scrollToBottom() {
        messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    function appendMessage(role, textOrHtml, isHtml = false) {
        const row = document.createElement("div");
        row.className = "msg " + (role === "user" ? "msg-user" : "msg-bot");
        if (isHtml) row.innerHTML = textOrHtml;
        else row.textContent = textOrHtml;
        messagesEl.appendChild(row);
        scrollToBottom();
        return row;
    }

    function updateMessage(el, newText) {
        if (!el) return;
        el.textContent = newText;
        scrollToBottom();

        // Update last assistant message in log (the "Thinking..." placeholder)
        for (let i = chatLog.length - 1; i >= 0; i--) {
            if (chatLog[i].role === "assistant") {
                chatLog[i].text = String(newText || "");
                break;
            }
        }
    }


    function setBusy(isBusy) {
        input.disabled = isBusy;
        if (sendBtn) sendBtn.disabled = isBusy;
        if (resetBtn) resetBtn.disabled = isBusy;
    }

    async function loadUploadsIntoMeta() {
        const filesMeta = document.getElementById("filesMeta");
        if (!filesMeta) return;

        try {
            const res = await fetch("/api/uploads");
            const data = await res.json();

            if (!data.ok) {
                filesMeta.textContent = "Documents: (could not load)";
                return;
            }

            const files = data.files || [];
            if (!files.length) {
                filesMeta.textContent = "Documents (0): none";
                return;
            }

            filesMeta.textContent = `Documents (${files.length}): ${files.map(f => f.original).join(" • ")}`;
        } catch (e) {
            filesMeta.textContent = "Documents: (could not load)";
        }
    }

    loadUploadsIntoMeta();

    // ---- NEW: Reset handler ----

    resetBtn.addEventListener("click", async () => {
        const confirm = await Swal.fire({
            icon: "warning",
            title: "Delete everything?",
            text: "All uploaded documents and the vector database will be deleted.",
            showCancelButton: true,
            confirmButtonText: "Yes, delete all",
            cancelButtonText: "Cancel",
        });

        if (!confirm.isConfirmed) return;

        setBusy(true);

        Swal.fire({
            title: "Deleting…",
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading()
        });

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

            if (!res.ok || !data.ok) {
                throw new Error(data.detail || data.message || "Delete failed");
            }

            await Swal.fire({
                icon: "success",
                title: "Deleted",
                text: "All uploads and vector DB data were removed. Returning to home…",
                timer: 900,
                showConfirmButton: false
            });

            sessionStorage.clear();
            window.location.href = "/";

        } catch (err) {
            await Swal.fire({
                icon: "error",
                title: "Delete failed",
                text: String(err)
            });
        } finally {
            setBusy(false);
        }
    });

    // ---- Chat submit ----
    form.addEventListener("submit", async (e) => {
        e.preventDefault();

        const text = input.value.trim();
        if (!text) return;

        appendMessage("user", text);

        input.value = "";
        input.focus();
        setBusy(true);

        const botMsg = appendMessage(
            "assistant",
            `Thinking <span class="dots"><span></span><span></span><span></span></span>`,
            true
        );
        botMsg.classList.add("thinking");

        try {
            const res = await fetch("/api/chat", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-LLM-Base-URL": baseUrl,
                    "X-LLM-API-Key": apiKey,
                    "X-LLM-Model": model,
                    "X-Embed-Model": embedModel
                },
                body: JSON.stringify({
                    message: text,
                    system: "You are a helpful assistant.",
                    temperature: 0.7,
                    top_k: 3
                })
            });

            let data;
            try { data = await res.json(); }
            catch { data = { reply: await res.text() }; }

            botMsg.classList.remove("thinking");

            if (!res.ok) {
                updateMessage(botMsg, data.detail || data.reply || `Server error (${res.status})`);
                return;
            }

            updateMessage(botMsg, data.reply ?? "(empty response)");

        } catch (err) {
            botMsg.classList.remove("thinking");
            updateMessage(botMsg, "Network error: " + String(err));
        } finally {
            setBusy(false);
            input.focus();
        }
    });

    const chatLog = [];

    function appendMessage(role, textOrHtml, isHtml = false) {
        const row = document.createElement("div");
        row.className = "msg " + (role === "user" ? "msg-user" : "msg-bot");
        if (isHtml) row.innerHTML = textOrHtml;
        else row.textContent = textOrHtml;

        messagesEl.appendChild(row);
        scrollToBottom();

        // Log only plain text
        const textForLog = isHtml ? row.textContent : String(textOrHtml || "");
        chatLog.push({ role: role === "user" ? "user" : "assistant", text: textForLog });

        return row;
    }


    saveBtn.addEventListener("click", async () => {
        if (!chatLog.length) {
            Swal.fire({ icon: "info", title: "Nothing to save", text: "Chat is empty." });
            return;
        }

        try {
            setBusy(true);

            const filesMetaEl = document.getElementById("filesMeta");
            const metaText =
                (metaEl ? metaEl.textContent : "") +
                "\n" +
                (filesMetaEl ? filesMetaEl.textContent : "");

            const res = await fetch("/api/export_chat_pdf", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    title: "ECDA LLM Chat Export",
                    meta: metaText,
                    messages: chatLog
                })
            });

            if (!res.ok) {
                const t = await res.text();
                throw new Error(t || `Export failed (${res.status})`);
            }

            const blob = await res.blob();
            const url = URL.createObjectURL(blob);

            const a = document.createElement("a");
            a.href = url;

            const cd = res.headers.get("Content-Disposition") || "";
            const match = cd.match(/filename="([^"]+)"/i);
            a.download = match ? match[1] : "ecda_chat_export.pdf";

            document.body.appendChild(a);
            a.click();
            a.remove();

            URL.revokeObjectURL(url);

            Swal.close();
            await Swal.fire({ icon: "success", title: "Saved", timer: 800, showConfirmButton: false });

        } catch (err) {
            await Swal.fire({ icon: "error", title: "Save failed", text: String(err) });
        } finally {
            setBusy(false);
        }
    });



</script>
{% endblock %}