"""Sudo-Passwort-Modal — fragt das Passwort einmal ab und gibt es zurück."""
from __future__ import annotations

from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.screen import ModalScreen
from textual.widgets import Input, Static

from taninux.core import theme as T


class SudoModal(ModalScreen[str | None]):
    """Fragt sudo-passwort. Liefert das Passwort oder None bei abbruch.

    Eingabe ist gemaskt. Das Passwort wird NICHT geloggt oder gespeichert —
    nur an `sudo -S -v` weitergereicht zum cachen."""

    BINDINGS = [
        Binding("escape", "cancel", "abbruch"),
    ]

    CSS = f"""
    SudoModal {{
        align: center middle;
        background: rgba(0, 0, 0, 0.6);
    }}
    SudoModal #sudo-dialog {{
        width: auto;
        max-width: 70;
        height: auto;
        padding: 1 3;
        background: {T.YORU};
        border: round {T.BASE3};
    }}
    SudoModal Static {{
        background: {T.YORU};
        margin-bottom: 1;
    }}
    SudoModal Input {{
        background: {T.BASE1};
        color: {T.YUKI};
        border: round {T.BASE2};
    }}
    SudoModal Input:focus {{
        border: round {T.UME};
    }}
    SudoModal #sudo-hint {{
        margin-top: 1;
        margin-bottom: 0;
        color: {T.BASE4};
    }}
    """

    def compose(self) -> ComposeResult:
        with Vertical(id="sudo-dialog"):
            yield Static(f"[{T.UME}]sudo passwort[/]", markup=True)
            yield Static(
                f"[{T.BASE5}]wird via sudo -S -v gecached (5 min ttl), "
                f"dann updates laufen im TUI.[/]",
                markup=True,
            )
            yield Input(password=True, id="sudo-pw")
            yield Static(
                f"[{T.BASE5}]ENTER[/] [{T.BASE4}]bestätigen[/]   "
                f"[{T.BASE5}]ESC[/] [{T.BASE4}]abbrechen[/]",
                id="sudo-hint",
                markup=True,
            )

    def on_mount(self) -> None:
        self.query_one(Input).focus()

    def on_input_submitted(self, event: Input.Submitted) -> None:
        self.dismiss(event.value)

    def action_cancel(self) -> None:
        self.dismiss(None)
