"""Agent installation modal for missing CLI tools."""

from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING

from textual.containers import Container, Horizontal
from textual.screen import ModalScreen
from textual.widgets import Button, Label, LoadingIndicator, Static

if TYPE_CHECKING:
    from textual.app import ComposeResult

    from kagan.builtin_agents import BuiltinAgent


class AgentInstallModal(ModalScreen[bool | None]):
    """Modal for installing a missing agent CLI.

    Returns:
        True  - Install succeeded
        None  - User cancelled or install failed and user chose not to retry
    """

    BINDINGS = [("escape", "cancel", "Cancel")]

    def __init__(self, agent: BuiltinAgent) -> None:
        super().__init__()
        self._agent = agent
        self._installing = False

    def compose(self) -> ComposeResult:
        name = self._agent.config.name

        with Container(id="agent-install-container"):
            yield Label(f"Install {name}", id="agent-install-title")
            yield Static(
                f"{self._agent.description}\nBy {self._agent.author}",
                id="agent-install-description",
            )
            yield Static(
                f"$ {self._agent.install_command}",
                id="agent-install-command",
            )
            yield LoadingIndicator(id="agent-install-spinner")
            yield Static("", id="agent-install-status")

            with Horizontal(id="agent-install-buttons"):
                yield Button("Install", variant="primary", id="install-btn")
                yield Button("Cancel", id="cancel-btn")

    def on_mount(self) -> None:
        self.query_one("#agent-install-spinner", LoadingIndicator).display = False
        self.query_one("#agent-install-status", Static).display = False

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "install-btn":
            self._do_install()
        elif event.button.id == "cancel-btn":
            self.dismiss(None)

    def _do_install(self) -> None:
        if self._installing:
            return
        self._installing = True

        self.query_one("#agent-install-buttons", Horizontal).display = False
        self.query_one("#agent-install-spinner", LoadingIndicator).display = True
        status = self.query_one("#agent-install-status", Static)
        status.update("Installing...")
        status.display = True

        self.run_worker(self._run_install(), group="agent-install")

    async def _run_install(self) -> None:
        from kagan.agents.installer import install_agent

        success, message = await install_agent(self._agent.config.short_name)

        self.query_one("#agent-install-spinner", LoadingIndicator).display = False

        status = self.query_one("#agent-install-status", Static)

        if success:
            status.update(f"[green]{message}[/green]")
            await asyncio.sleep(1.5)
            self.dismiss(True)
        else:
            status.update(f"[red]{message}[/red]")
            self.query_one("#agent-install-buttons", Horizontal).display = True
            self.query_one("#install-btn", Button).label = "Retry"
            self._installing = False

    def action_cancel(self) -> None:
        if not self._installing:
            self.dismiss(None)
