"""Auth commands: login, logout, whoami - registered directly on the root app."""

from __future__ import annotations

import typer
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn


def register_auth_commands(app: typer.Typer) -> None:
    """Register auth commands on the given Typer app."""
    console = Console()

    @app.command()
    def login(
        token: str = typer.Option(
            None,
            "--token",
            "-t",
            help="API token (skip browser flow)",
        ),
        no_browser: bool = typer.Option(
            False,
            "--no-browser",
            help="Don't open browser, just display the URL",
        ),
    ) -> None:
        """Log in to Appliku via browser or with an API token."""
        from appliku._auth import DeviceAuthFlow, save_token

        # If token provided directly, use it
        if token:
            save_token(token)
            console.print("[green]Token saved successfully.[/green]")
            return

        # Start browser-based flow
        console.print("\n[bold]Logging in to Appliku...[/bold]\n")

        flow = DeviceAuthFlow()

        try:
            flow.initiate()
        except Exception as e:
            console.print(f"[red]Failed to start login flow: {e}[/red]")
            raise typer.Exit(1) from e

        # Display the code
        console.print(f"Your authorization code: [bold cyan]{flow.user_code}[/bold cyan]\n")

        # Try to open browser
        browser_opened = False
        if not no_browser:
            browser_opened = flow.open_browser()

        if browser_opened:
            console.print("[dim]Opening browser to complete login...[/dim]")
            console.print("[dim]If browser doesn't open, visit:[/dim]")
        else:
            console.print("Open this URL in your browser:")

        url = flow.verification_url_complete
        console.print(f"  [link={url}]{url}[/link]\n")

        # Poll for authorization
        console.print("[dim]Waiting for authorization...[/dim]")

        def on_pending(elapsed: int) -> None:
            remaining = flow.expires_in - elapsed
            if remaining > 0 and elapsed % 30 == 0 and elapsed > 0:
                console.print(f"[dim]Still waiting... ({remaining}s remaining)[/dim]")

        try:
            with Progress(
                SpinnerColumn(),
                TextColumn("[progress.description]{task.description}"),
                console=console,
                transient=True,
            ) as progress:
                progress.add_task(description="Waiting for browser authorization...", total=None)
                api_token = flow.wait_for_authorization(on_pending=on_pending)
        except KeyboardInterrupt:
            console.print("\n[yellow]Login cancelled.[/yellow]")
            raise typer.Exit(1) from None
        finally:
            flow.close()

        if api_token:
            save_token(api_token)
            console.print("\n[green]Successfully logged in![/green]")

            # Show who we logged in as
            try:
                from appliku import Appliku

                client = Appliku(token=api_token)
                user_info = client._client.get("/api/user_info/")
                console.print(f"Authenticated as: [bold]{user_info.get('email')}[/bold]")
            except Exception:  # noqa: S110
                pass
        else:
            console.print("\n[red]Login failed or was denied.[/red]")
            console.print("[dim]You can also log in with a token:[/dim]")
            console.print("  appliku login --token YOUR_TOKEN")
            raise typer.Exit(1)

    @app.command()
    def logout() -> None:
        """Remove saved API token."""
        from appliku._auth import CONFIG_PATH

        if CONFIG_PATH.exists():
            CONFIG_PATH.unlink()
            console.print("[green]Logged out.[/green]")
        else:
            console.print("[yellow]Not logged in.[/yellow]")

    @app.command()
    def whoami() -> None:
        """Show current authenticated user."""
        from appliku.cli import get_client

        client = get_client()
        user = client._client.get("/api/user_info/")
        console.print(f"Email: [bold]{user.get('email')}[/bold]")
        console.print(f"Name: {user.get('name', 'N/A')}")
