"""Install screen — orchestrates the 15-step install flow."""

from __future__ import annotations

import asyncio

from textual.app import ComposeResult
from textual.screen import Screen
from textual.widgets import Header, Footer, Static
from textual.containers import Container

from easyclaw_tui.state import InstallState, StepStatus
from easyclaw_tui.widgets.step_progress import StepProgress
from easyclaw_tui.widgets.step_panel import StepPanel
from easyclaw_tui.widgets.chat_panel import ChatPanel
from easyclaw_tui.api.client import MCPClient

from easyclaw_tui.steps.base import StepResult
from easyclaw_tui.steps.s01_preflight import PreflightStep
from easyclaw_tui.steps.s02_nodejs import NodejsStep
from easyclaw_tui.steps.s03_openclaw import OpenClawStep
from easyclaw_tui.steps.s04_tools import ToolsStep
from easyclaw_tui.steps.s05_config import ConfigStep
from easyclaw_tui.steps.s06_token import TokenStep
from easyclaw_tui.steps.s07_write_config import WriteConfigStep
from easyclaw_tui.steps.s08_env_vars import EnvVarsStep
from easyclaw_tui.steps.s09_workspace import WorkspaceStep
from easyclaw_tui.steps.s10_validate import ValidateStep
from easyclaw_tui.steps.s11_init_gateway import InitGatewayStep
from easyclaw_tui.steps.s12_systemd import SystemdStep
from easyclaw_tui.steps.s13_mcp import McpStep
from easyclaw_tui.steps.s14_channel import ChannelStep
from easyclaw_tui.steps.s15_health import HealthStep


class InstallScreen(Screen):
    """Main install screen with sidebar, content panel, and chat."""

    BINDINGS = []

    def __init__(self, state: InstallState) -> None:
        super().__init__()
        self.state = state
        self._step_classes = [
            PreflightStep,
            NodejsStep,
            OpenClawStep,
            ToolsStep,
            ConfigStep,
            TokenStep,
            WriteConfigStep,
            EnvVarsStep,
            WorkspaceStep,
            ValidateStep,
            InitGatewayStep,
            SystemdStep,
            McpStep,
            ChannelStep,
            HealthStep,
        ]
        self._chat_visible = False

    def compose(self) -> ComposeResult:
        yield Header()
        yield StepProgress(self.state)
        yield StepPanel(self.state)
        yield ChatPanel()
        yield Footer()

    @property
    def progress(self) -> StepProgress:
        return self.query_one(StepProgress)

    @property
    def panel(self) -> StepPanel:
        return self.query_one(StepPanel)

    @property
    def chat(self) -> ChatPanel:
        return self.query_one(ChatPanel)

    def toggle_chat(self) -> None:
        self._chat_visible = not self._chat_visible
        chat = self.chat
        if self._chat_visible:
            chat.add_class("--visible")
        else:
            chat.remove_class("--visible")

    async def on_mount(self) -> None:
        # Start the install flow
        self.run_worker(self._run_install())

    async def _run_install(self) -> None:
        """Execute steps sequentially."""
        for i, step_cls in enumerate(self._step_classes):
            step_num = i + 1
            step_info = self.state.steps[i]

            # Update UI
            self.state.set_step_status(step_num, StepStatus.RUNNING)
            self.progress.refresh_steps()
            self.panel.set_step(step_num, step_info.name)

            # Create and run the step
            step = step_cls(self.state, self.panel)
            try:
                result = await step.run()
            except Exception as e:
                self.panel.log_error(f"Step failed with exception: {e}")
                result = StepResult(success=False, message=str(e))

            # Update status
            if result.success:
                self.state.set_step_status(step_num, StepStatus.SUCCESS)
            elif result.skipped:
                self.state.set_step_status(step_num, StepStatus.SKIPPED)
            else:
                self.state.set_step_status(step_num, StepStatus.FAILED)
                self.panel.log_error(f"Step {step_num} failed: {result.message}")
                # On failure, offer Foreman diagnosis
                if self.state.api_key:
                    self.panel.log_info("Asking Foreman for help...")
                    try:
                        client = MCPClient(self.state.api_key)
                        diagnosis = await client.diagnose(result.message)
                        self.panel.log_raw(f"\n[bold #f59e0b]Foreman says:[/bold #f59e0b]\n{diagnosis}")
                    except Exception:
                        self.panel.log_warn("Could not reach Foreman — check API key")
                # Ask whether to continue or abort
                self.panel.log_raw("\n[bold]Press Enter to continue or Ctrl+C to abort[/bold]")
                # Continue to next step after brief pause
                await asyncio.sleep(2)

            self.progress.refresh_steps()
            self.state.current_step = step_num + 1

        # All done
        self.panel.log_raw("\n[bold green]Installation complete![/bold green]")

    async def on_chat_panel_chat_submitted(self, event: ChatPanel.ChatSubmitted) -> None:
        """Handle chat messages by routing to the best MCP tool."""
        if not self.state.api_key:
            self.chat.add_system_message("Set your API key first (Step 5)")
            return

        from easyclaw_tui.api.client import route_query

        tool_name, _ = route_query(event.text)
        self.chat.add_system_message(f"Using {tool_name}...")

        try:
            client = MCPClient(self.state.api_key)
            response = await client.smart_query(event.text)
            self.chat.add_bot_message(response)
        except Exception as e:
            self.chat.add_system_message(f"Error: {e}")
