"""Interactive credential retrieval screen for the ALiCE TUI."""

from __future__ import annotations

from typing import TYPE_CHECKING

from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import Screen
from textual.widgets import Button, Footer, Input, Label, Select

from alice_cli.errors import AliceCLIError
from alice_cli.models import OutputFormat
from alice_cli.tui.widgets.clock import TerminalClock
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

_FORMAT_OPTIONS: list[tuple[str, OutputFormat]] = [
    ("export", OutputFormat.EXPORT),
    ("eval", OutputFormat.EVAL),
    ("dotenv", OutputFormat.DOTENV),
    ("json", OutputFormat.JSON),
]


class GetKeyScreen(Screen[None]):
    """Interactive credential retrieval screen."""

    BINDINGS = [
        Binding("escape", "pop_screen", "Back"),
    ]

    def compose(self) -> ComposeResult:
        config = self.app.alice_config  # type: ignore[attr-defined]
        default_profile = config.profile or ""

        yield AliceHeaderBar()
        with Vertical():
            yield Label("Retrieve Bedrock Credentials", id="get-key-title")
            yield Label("Profile:")
            yield Input(value=default_profile, placeholder="AWS profile name", id="profile-input")
            yield Label("Format:")
            yield Select[OutputFormat](
                _FORMAT_OPTIONS,
                value=OutputFormat.EXPORT,
                id="format-select",
            )
            yield Button("Retrieve", id="btn-retrieve", variant="primary")
            yield OutputPanel(id="output-panel")
        yield TerminalClock()
        yield Footer()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle the Retrieve button press."""
        if event.button.id != "btn-retrieve":
            return
        self._retrieve_credentials()

    def _retrieve_credentials(self) -> None:
        """Run the credential retrieval workflow and display results."""
        from alice_cli.auth import detect_username
        from alice_cli.formatting import format_credentials
        from alice_cli.secrets import build_secret_path, fetch_credentials

        config = self.app.alice_config  # type: ignore[attr-defined]

        profile_input = self.query_one("#profile-input", Input)
        format_select = self.query_one("#format-select", Select)
        output = self.query_one("#output-panel", OutputPanel)

        profile = profile_input.value.strip() or None
        fmt = (
            format_select.value
            if isinstance(format_select.value, OutputFormat)
            else OutputFormat.EXPORT
        )

        output.clear()

        try:
            result = detect_username(profile, config.region)
            secret_path = build_secret_path(config.namespace, config.environment, result.username)
            creds = fetch_credentials(profile, config.region, secret_path)
            formatted = format_credentials(creds, fmt, result.username, result.session_name)
            output.write(formatted)
        except AliceCLIError as exc:
            output.write(f"[#FF6600]Error: {exc.format_message()}[/]")
        except Exception as exc:
            output.write(f"[#FF6600]Unexpected error: {exc}[/]")
