"""Get-secret screen for the ALiCE TUI — fetch secrets and list inference profiles."""

from __future__ import annotations

from typing import TYPE_CHECKING

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

from alice_cli.errors import AliceCLIError
from alice_cli.tui.screens.base import AliceScreen
from alice_cli.tui.widgets.clock import TerminalClock
from alice_cli.tui.widgets.output import OutputPanel

if TYPE_CHECKING:
    from textual.app import ComposeResult


class GetSecretScreen(AliceScreen):
    """Fetch a secret by short name and display inference profiles."""

    DEFAULT_CSS = """
    GetSecretScreen #profiles-panel {
        height: auto;
        min-height: 4;
        max-height: 12;
    }
    """

    def compose(self) -> ComposeResult:
        with Vertical():
            yield Label("Get Secret", id="get-secret-title")
            yield Label("Secret short name (leave blank for your Bedrock key):")
            yield Input(placeholder="e.g. bedrock-api-keys/user@jhu.edu", id="secret-name-input")
            yield Button("Fetch", id="btn-fetch", variant="primary")
            yield OutputPanel(id="output-panel")
            yield Label("Inference Profiles", id="profiles-title")
            yield OutputPanel(id="profiles-panel")
        yield TerminalClock()
        yield Footer()

    def on_mount(self) -> None:
        self._load_profiles()

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

    def _load_profiles(self) -> None:
        """Display inference profile ARNs from the loaded config."""
        config = self.config
        panel = self.query_one("#profiles-panel", OutputPanel)
        panel.clear()

        arns = config.inference_profile_arns
        if not arns:
            panel.write("[dim]No inference profiles mapped (using direct model IDs)[/dim]")
            return

        lines: list[str] = []
        lines.append(f"  {len(arns)} model(s) mapped")
        for alias, arn in sorted(arns.items()):
            short_arn = arn if len(arn) <= 44 else f"…{arn[-42:]}"
            lines.append(f"    {alias:<18} {short_arn}")
        panel.write("\n".join(lines))

    def _fetch_secret(self) -> None:
        """Fetch the requested secret and display it."""
        from botocore.exceptions import ClientError

        from alice_cli.auth import detect_username
        from alice_cli.commands.get_secret import (
            _check_bedrock_access,
            build_short_name_path,
        )

        name_input = self.query_one("#secret-name-input", Input)
        output = self.query_one("#output-panel", OutputPanel)
        output.clear()

        try:
            result = detect_username(self.config.profile, self.config.region)
        except AliceCLIError as exc:
            self._handle_error(exc, output)
            return

        name = name_input.value.strip() or f"bedrock-api-keys/{result.username}@jhu.edu"
        full_path = build_short_name_path(self.config.namespace, self.config.environment, name)

        try:
            _check_bedrock_access(full_path, result.username)
        except AliceCLIError as exc:
            self._handle_error(exc, output)
            return

        output.write(f"Fetching: {full_path}")

        try:
            session = self._create_session()
            client = session.client("secretsmanager")
            response = client.get_secret_value(SecretId=full_path)
            output.write(response["SecretString"])
        except ClientError as exc:
            self._handle_error(exc, output)
        except Exception as exc:
            self._handle_error(exc, output)
