"""
Magi Bot UI starter — Tkinter
=============================
This file is a host window so you can see how Magi Bot is wired.

It is NOT Magi's UI.
It is NOT a professional interface.
It exists so you can get started, then throw it away and write your own.

magi_bot.py does not open a window. There is no ``if __name__ == "__main__"``.
You put this (or any other UI) in a *separate* file next to magi_bot.py:

    python magi-bot-ui-starter.py
"""

from __future__ import annotations

import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

# magi_bot.py imports formatter.format_markdown_and_latex at load time.
# formatter.py is required in this folder. Do not stub it.
_formatter = HERE / "formatter.py"
if not _formatter.exists():
    raise SystemExit(
        "formatter.py is required next to magi_bot.py.\n"
        "Download it from the Magi Bot page and put it in this folder."
    )

import tkinter as tk
from tkinter import simpledialog

try:
    from magi_bot import BotWorkspaceTools, bot_manager
except Exception as exc:  # noqa: BLE001 — starter should stay noisy
    raise SystemExit(
        "Could not import magi_bot.py. Put this starter in the same folder.\n"
        f"Import error: {exc}"
    ) from exc


class StarterWindow(tk.Tk):
    def __init__(self) -> None:
        super().__init__()
        self.title("Magi Bot — starter UI (not professional)")
        self.geometry("720x480")
        self.minsize(560, 360)

        warn = tk.Label(
            self,
            text="Starter host only. Replace this file with your own UI.",
            anchor="w",
            fg="#7a3b00",
            bg="#f3e6d4",
            padx=10,
            pady=6,
        )
        warn.pack(fill="x")

        body = tk.PanedWindow(self, sashrelief="flat")
        body.pack(fill="both", expand=True)

        side = tk.Frame(body, width=200)
        self.bot_list = tk.Listbox(side, exportselection=False)
        self.bot_list.pack(fill="both", expand=True, padx=8, pady=8)
        self.bot_list.bind("<<ListboxSelect>>", self.on_select)
        tk.Button(side, text="Refresh bots", command=self.refresh_bots).pack(
            fill="x", padx=8, pady=(0, 8)
        )
        body.add(side)

        chat = tk.Frame(body)
        self.log = tk.Text(chat, wrap="word", state="disabled", height=16)
        self.log.pack(fill="both", expand=True, padx=8, pady=8)
        row = tk.Frame(chat)
        row.pack(fill="x", padx=8, pady=(0, 8))
        self.entry = tk.Entry(row)
        self.entry.pack(side="left", fill="x", expand=True)
        self.entry.bind("<Return>", lambda _e: self.send())
        tk.Button(row, text="Send", command=self.send).pack(side="left", padx=(8, 0))
        tk.Button(row, text="Demo: create file", command=self.demo_create).pack(
            side="left", padx=(8, 0)
        )
        body.add(chat)

        self.active_id: str | None = None
        self.refresh_bots()
        self.note(
            "This starter only stores messages and can run one confirmed "
            "workspace action. Real model steps use MagiBotWorker inside a "
            "host you write. Do not ship this window."
        )

    def note(self, text: str) -> None:
        self.log.configure(state="normal")
        self.log.insert("end", text.rstrip() + "\n\n")
        self.log.configure(state="disabled")
        self.log.see("end")

    def refresh_bots(self) -> None:
        self.bot_list.delete(0, "end")
        self._bots = bot_manager.get_all_bots()
        for bot in self._bots:
            self.bot_list.insert("end", f"{bot.get('name', 'Bot')}  [{bot.get('model', '')}]")
        if self._bots:
            self.bot_list.selection_set(0)
            self.on_select()

    def on_select(self, _event: object | None = None) -> None:
        sel = self.bot_list.curselection()
        if not sel:
            return
        bot = self._bots[sel[0]]
        self.active_id = bot.get("id")
        self.note(f"Selected {bot.get('name')} — workspace {bot.get('workspace_dir')}")

    def send(self) -> None:
        text = self.entry.get().strip()
        self.entry.delete(0, "end")
        if not text or not self.active_id:
            return
        bot_manager.add_message(self.active_id, "user", text)
        self.note(f"You: {text}")
        self.note(
            "Starter does not call a model. In your UI, pass this text into "
            "MagiBotWorker (PyQt host) or your own inference loop. Confirm only "
            "when a move would take a file outside Magi(name)."
        )

    def demo_create(self) -> None:
        if not self.active_id:
            return
        bot = bot_manager.get_bot(self.active_id)
        if not bot:
            return
        rel = simpledialog.askstring("Create file", "Relative path inside the workspace:", initialvalue="notes.txt")
        if not rel:
            return
        ok, msg = BotWorkspaceTools.create_file(bot["workspace_dir"], rel, "hello from the starter UI\n")
        bot_manager.add_message(self.active_id, "system", msg, action={"type": "create_file", "path": rel})
        self.note(("OK: " if ok else "Failed: ") + msg)


if __name__ == "__main__":
    StarterWindow().mainloop()
