"""Session and config status screen for the ALiCE TUI."""

from __future__ import annotations

from typing import TYPE_CHECKING

from textual.containers import Vertical
from textual.widgets import Button, Footer, Label

from alice_cli.errors import AliceCLIError
from alice_cli.tui.screens.base import AliceScreen
from alice_cli.tui.widgets.breadcrumb import BreadcrumbBar
from alice_cli.tui.widgets.header_bar import AliceHeaderBar
from alice_cli.tui.widgets.output import OutputPanel

if TYPE_CHECKING:
    from textual.app import ComposeResult


class StatusScreen(AliceScreen):
    """Displays session identity and resolved config as a centered floating box."""

    DEFAULT_CSS = """
    StatusScreen {
        align: center middle;
    }

    StatusScreen #btn-refresh {
        width: 100%;
        margin-top: 1;
    }
    """

    def compose(self) -> ComposeResult:
        yield AliceHeaderBar()
        yield BreadcrumbBar(id="breadcrumb")
        with Vertical(id="status-box", classes="alice-panel"):
            yield Label("Session & Config Status", id="status-title", classes="alice-panel-title")
            yield OutputPanel(id="output-panel", wordstar=self._wordstar)
            yield Button("Refresh", id="btn-refresh", variant="primary")
        yield Footer()

    def on_mount(self) -> None:
        """Populate the output panel on first load."""
        self._refresh_status()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "btn-refresh":
            self._refresh_status()

    def _refresh_status(self) -> None:
        """Gather status info and write it to the output panel."""
        from alice_cli import __version__
        from alice_cli.auth import detect_identity_from_key, detect_username

        config = self.config
        output = self.query_one("#output-panel", OutputPanel)
        output.clear()

        lines: list[str] = []

        # Version
        lines.append(f"  Version     {__version__}")
        lines.append("")

        # Auth & identity
        auth_mode = "unknown"
        try:
            result = detect_username(config.profile, config.region)
            auth_mode = "SSO"
            lines.append(f"  Auth        {auth_mode}")
            lines.append(f"  JHED        {result.username}")
            lines.append(f"  Session     {result.session_name}")
            account = result.arn.split(":")[4]
            lines.append(f"  Account     {account}")
        except AliceCLIError as exc:
            if config.bedrock_secret_key and not config.profile:
                auth_mode = "API key (SSO bypassed)"
                identity = detect_identity_from_key(config.bedrock_access_key)
                lines.append(f"  Auth        {auth_mode}")
                if identity and identity != "unknown":
                    lines.append(f"  Identity    {identity}")
            else:
                # Flush lines collected so far, then delegate to _handle_error
                output.write("\n".join(lines))
                lines.clear()
                self._handle_error(exc, output)

        lines.append("")

        # Config
        lines.append(f"  Region      {config.region}")
        lines.append(f"  Namespace   {config.namespace}")
        lines.append(f"  Environment {config.environment}")

        output.write("\n".join(lines))
