"""Main EasyClaw TUI application."""

from __future__ import annotations

import logging
import logging.handlers
from pathlib import Path

from textual.app import App, ComposeResult
from textual.binding import Binding

from easyclaw_tui.state import InstallState

# Re-export for convenience
from easyclaw_tui.state import StepStatus, StepInfo, MODEL_MAP  # noqa: F401


def _silence_logging_for_tui() -> None:
    """Redirect all agent logging to a file so nothing writes to stderr.

    Without this, Python's lastResort handler writes WARNING+ messages
    directly to stderr, which corrupts Textual's terminal rendering.
    """
    log_dir = Path.home() / ".easyclaw"
    log_dir.mkdir(parents=True, exist_ok=True)
    log_file = log_dir / "tui.log"

    handler = logging.handlers.RotatingFileHandler(
        str(log_file), maxBytes=2_000_000, backupCount=1,
    )
    handler.setFormatter(
        logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
    )

    # Capture all agent-related loggers
    for name in ("foreman", "tui_bridge"):
        logger = logging.getLogger(name)
        logger.handlers.clear()
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        logger.propagate = False  # Don't bubble up to root/lastResort

    # Also silence httpx and httpcore (they log request details)
    for name in ("httpx", "httpcore"):
        logger = logging.getLogger(name)
        logger.handlers.clear()
        logger.addHandler(logging.NullHandler())
        logger.propagate = False


class EasyClawApp(App):
    """EasyClaw interactive installer."""

    TITLE = "EasyClaw"
    SUB_TITLE = "Agent Johnny 5"
    CSS_PATH = "styles/app.tcss"

    BINDINGS = [
        Binding("q", "quit", "Quit", show=True),
        Binding("ctrl+c", "quit", "Quit", show=False),
    ]

    def __init__(
        self,
        mode: str = "install",
        api_key: str = "",
        openrouter_key: str = "",
        openai_key: str = "",
        model: str = "",
        channel: str = "none",
        bind: str = "lan",
    ) -> None:
        # Silence logging BEFORE anything else initializes
        _silence_logging_for_tui()
        super().__init__()
        self.install_state = InstallState(
            api_key=api_key,
            openrouter_key=openrouter_key,
            openai_key=openai_key,
            model=model,
            channel=channel,
            bind=bind,
        )
        self.mode = mode

    def on_mount(self) -> None:
        if self.mode == "help":
            from easyclaw_tui.screens.help import HelpScreen

            self.push_screen(HelpScreen(self.install_state))
        else:
            from easyclaw_tui.screens.install import InstallScreen

            self.push_screen(InstallScreen(self.install_state))
