"""Handler for /auth command."""

from rich.console import Console

from ....design import print_error

console = Console()


def handle_auth(args: str) -> None:
    """Handle /auth command.

    Args:
        args: Command arguments
    """
    from emdash_core.auth.github import GitHubAuth, get_auth_status

    # Parse subcommand
    subparts = args.split(maxsplit=1) if args else []
    subcommand = subparts[0].lower() if subparts else "status"

    if subcommand == "status" or subcommand == "":
        # Show auth status
        status = get_auth_status()
        console.print()
        console.print("[bold cyan]GitHub Authentication[/bold cyan]\n")

        if status["authenticated"]:
            console.print(f"  Status: [green]Authenticated[/green]")
            console.print(f"  Source: {status['source']}")
            if status["username"]:
                console.print(f"  Username: @{status['username']}")
            if status["scopes"]:
                console.print(f"  Scopes: {', '.join(status['scopes'])}")
        else:
            console.print(f"  Status: [yellow]Not authenticated[/yellow]")
            console.print("\n[dim]Run /auth login to authenticate with GitHub[/dim]")

        console.print()

    elif subcommand == "login":
        # Start GitHub OAuth device flow
        console.print()
        console.print("[bold cyan]GitHub Login[/bold cyan]")
        console.print("[dim]Starting device authorization flow...[/dim]\n")

        auth = GitHubAuth()
        try:
            config = auth.login(open_browser=True)
            if config:
                console.print()
                console.print("[green]Authentication successful![/green]")
                console.print("[dim]MCP servers can now use ${GITHUB_TOKEN}[/dim]")
            else:
                console.print("[red]Authentication failed or was cancelled.[/red]")
        except Exception as e:
            print_error(e, "Login failed")

        console.print()

    elif subcommand == "logout":
        # Remove stored authentication
        auth = GitHubAuth()
        if auth.logout():
            console.print("[green]Logged out successfully[/green]")
        else:
            console.print("[dim]No stored authentication to remove[/dim]")

    else:
        console.print(f"[yellow]Unknown subcommand: {subcommand}[/yellow]")
        console.print("[dim]Usage: /auth [status|login|logout][/dim]")
