// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { DeepsearchProgressSocket } from "./DeepsearchProgressSocket.js";

export class DeepsearchTool {
    constructor() {
        this.root = document.querySelector("[data-deepsearch-tool]");
        if (!this.root) return;
        this.form = this.root.querySelector("[data-deepsearch-form]");
        this.errorBox = this.root.querySelector("[data-deepsearch-error]");
        this.live = this.root.querySelector("[data-deepsearch-live]");
        this.statusText = this.root.querySelector("[data-deepsearch-status]");
        this.countText = this.root.querySelector("[data-deepsearch-count]");
        this.bar = this.root.querySelector("[data-deepsearch-bar]");
        this.log = this.root.querySelector("[data-deepsearch-log]");
        this.done = this.root.querySelector("[data-deepsearch-done]");
        this.openLink = this.root.querySelector("[data-deepsearch-open]");
        this.pauseBtn = this.root.querySelector("[data-deepsearch-pause]");
        this.resumeBtn = this.root.querySelector("[data-deepsearch-resume]");
        this.cancelBtn = this.root.querySelector("[data-deepsearch-cancel]");
        this.runBtn = this.form.querySelector("[data-deepsearch-run]");
        this.socket = null;
        this.uid = null;
        this._bind();
    }

    _bind() {
        this.form.addEventListener("submit", (event) => {
            event.preventDefault();
            this._start();
        });
        this.pauseBtn.addEventListener("click", () => this._control("pause"));
        this.resumeBtn.addEventListener("click", () => this._control("resume"));
        this.cancelBtn.addEventListener("click", () => this._control("cancel"));
    }

    async _start() {
        this._setError("");
        const query = this.form.query.value.trim();
        if (!query) return;
        const params = {
            query,
            depth: this.form.depth ? this.form.depth.value : 2,
            max_pages: this.form.max_pages ? this.form.max_pages.value : 12,
        };
        this._resetLive();
        try {
            const data = await Http.send("/tools/deepsearch/run", params);
            this.uid = data.uid;
            this._watch(data.uid);
        } catch (error) {
            this._setError(error.message || "Could not start the research.");
            this.live.hidden = true;
            this.runBtn.disabled = false;
        }
    }

    _resetLive() {
        if (this.socket) this.socket.close();
        this.done.hidden = true;
        this.live.hidden = false;
        this.log.innerHTML = "";
        this.bar.style.width = "0%";
        this.countText.textContent = "";
        this.statusText.textContent = "Starting…";
        this.runBtn.disabled = true;
        this.pauseBtn.hidden = false;
        this.resumeBtn.hidden = true;
        this.cancelBtn.hidden = false;
    }

    async _control(action) {
        if (!this.uid) return;
        try {
            await Http.send(`/tools/deepsearch/${this.uid}/${action}`, {});
        } catch (error) {
            this._setError(error.message || "Control failed.");
            return;
        }
        if (action === "pause") {
            this.pauseBtn.hidden = true;
            this.resumeBtn.hidden = false;
            this.statusText.textContent = "Paused";
        } else if (action === "resume") {
            this.pauseBtn.hidden = false;
            this.resumeBtn.hidden = true;
        } else if (action === "cancel") {
            this.pauseBtn.hidden = true;
            this.resumeBtn.hidden = true;
            this.cancelBtn.hidden = true;
            this.statusText.textContent = "Cancelling…";
        }
    }

    _watch(uid) {
        this.socket = new DeepsearchProgressSocket(uid, {
            onMessage: (frame) => this._frame(frame),
            onClose: () => {},
        });
        this.socket.connect();
    }

    _frame(frame) {
        const type = frame.type;
        if (type === "stage") {
            this.statusText.textContent = frame.message || "Working…";
            this._appendLog(frame.message || frame.stage);
        } else if (type === "queries") {
            this._appendLog(`Planned ${frame.queries.length} queries`);
        } else if (type === "candidates") {
            this._appendLog(`Found ${frame.count} candidate sources`);
        } else if (type === "progress") {
            const total = frame.total || 1;
            const done = frame.done || 0;
            this.bar.style.width = `${Math.round((done / total) * 100)}%`;
            this.countText.textContent = `${done} / ${total} sources`;
            if (frame.message) this.statusText.textContent = frame.message;
        } else if (type === "page_loaded") {
            this.bar.style.width = `${Math.round((frame.done / frame.total) * 100)}%`;
            this.countText.textContent = `${frame.done} / ${frame.total} sources`;
            this._appendLog(`${frame.source} ${frame.title || frame.url}`);
        } else if (type === "agent") {
            this.statusText.textContent = frame.message || "Analysing";
            this._appendLog(`Agent: ${frame.agent}`);
        } else if (type === "report_ready") {
            this.statusText.textContent = "Compiling report…";
        } else if (type === "done") {
            this.bar.style.width = "100%";
            this.statusText.textContent = "Done";
            this._finish(frame.session_url || `/tools/deepsearch/${this.uid}/session`);
        } else if (type === "failed") {
            this.statusText.textContent = "Failed";
            this._setError(frame.message || frame.error || "The research failed.");
            this.runBtn.disabled = false;
            this.pauseBtn.hidden = true;
            this.cancelBtn.hidden = true;
        }
    }

    _finish(sessionUrl) {
        this.runBtn.disabled = false;
        this.pauseBtn.hidden = true;
        this.resumeBtn.hidden = true;
        this.cancelBtn.hidden = true;
        this.done.hidden = false;
        this.openLink.href = sessionUrl;
    }

    _appendLog(text) {
        if (!text) return;
        const item = document.createElement("li");
        item.textContent = text;
        this.log.prepend(item);
    }

    _setError(message) {
        if (!this.errorBox) return;
        this.errorBox.textContent = message;
        this.errorBox.hidden = !message;
    }
}
