"""Help screen — post-install troubleshooting and diagnostics."""

from __future__ import annotations

from textual.app import ComposeResult
from textual.screen import Screen
from textual.widgets import Header, Footer, Static, RichLog, Input, Button
from textual.containers import Vertical, Horizontal

from easyclaw_tui.state import InstallState
from easyclaw_tui.api.client import MCPClient


QUICK_ACTIONS = [
    ("validate", "Validate Deployment", "validate_deployment"),
    ("security", "Security Audit", "security_audit"),
    ("gateway", "Troubleshoot Gateway", "troubleshoot_gateway"),
]


class HelpScreen(Screen):
    """Post-install troubleshooting with Foreman chat and quick actions."""

    BINDINGS = [
        ("escape", "app.pop_screen", "Back"),
    ]

    def __init__(self, state: InstallState) -> None:
        super().__init__()
        self.state = state

    def compose(self) -> ComposeResult:
        yield Header()
        with Vertical(id="help-container"):
            yield Static(
                "[bold #f59e0b]EasyClaw Foreman — Help & Diagnostics[/bold #f59e0b]",
                id="help-title",
            )
            yield Static(
                "Ask a question or run a quick diagnostic below.",
                id="help-subtitle",
            )

            # Quick action buttons
            with Horizontal(id="quick-actions"):
                for action_id, label, _ in QUICK_ACTIONS:
                    yield Button(label, id=f"btn-{action_id}", variant="primary")

            yield RichLog(id="help-log", wrap=True, highlight=True, markup=True)

            # Chat input
            with Horizontal(id="help-input-container"):
                yield Input(
                    placeholder="Describe your issue or ask a question...",
                    id="help-input",
                )
                yield Button("Ask", id="btn-ask", variant="primary")

        yield Footer()

    @property
    def log(self) -> RichLog:
        return self.query_one("#help-log", RichLog)

    def _get_client(self) -> MCPClient | None:
        if not self.state.api_key:
            self.log.write("[red]No API key set. Run the installer first.[/red]")
            return None
        return MCPClient(self.state.api_key)

    async def on_button_pressed(self, event: Button.Pressed) -> None:
        btn_id = event.button.id

        if btn_id == "btn-ask":
            await self._handle_ask()
        elif btn_id == "btn-validate":
            await self._run_action("Validating deployment...", "validate_deployment")
        elif btn_id == "btn-security":
            await self._run_action("Running security audit...", "security_audit")
        elif btn_id == "btn-gateway":
            inp = self.query_one("#help-input", Input)
            symptom = inp.value.strip() or "gateway not responding"
            await self._run_action(
                f"Troubleshooting gateway: {symptom}",
                "troubleshoot_gateway",
                {"symptom": symptom},
            )

    async def on_input_submitted(self, event: Input.Submitted) -> None:
        if event.input.id == "help-input":
            await self._handle_ask()

    async def _handle_ask(self) -> None:
        inp = self.query_one("#help-input", Input)
        text = inp.value.strip()
        if not text:
            return
        inp.value = ""

        self.log.write(f"\n[bold cyan]You:[/bold cyan] {text}")
        client = self._get_client()
        if not client:
            return

        self.log.write("[dim]Thinking...[/dim]")
        try:
            response = await client.smart_query(text)
            self.log.write(f"[bold #f59e0b]Foreman:[/bold #f59e0b] {response}")
        except Exception as e:
            self.log.write(f"[red]Error: {e}[/red]")

    async def _run_action(
        self, label: str, tool: str, args: dict | None = None
    ) -> None:
        self.log.write(f"\n[cyan]→ {label}[/cyan]")
        client = self._get_client()
        if not client:
            return

        try:
            result = await client.call_tool(tool, args or {})
            text = result.get("text", result.get("error", "No response"))
            self.log.write(f"[bold #f59e0b]Foreman:[/bold #f59e0b]\n{text}")
        except Exception as e:
            self.log.write(f"[red]Error: {e}[/red]")
