"""Context command — whoami, shows current user's accounts and roles."""

from __future__ import annotations

import typer

from turumba_cli.client import TurumbaClient
from turumba_cli.errors import TurumbaAuthError
from turumba_cli.output import console, error, render_json

app = typer.Typer(name="context", help="Show current user context (accounts, roles).")


@app.callback(invoke_without_command=True)
def whoami(
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Show the current authenticated user's accounts and roles."""
    client = TurumbaClient(gateway_url=gateway_url)

    try:
        context = client.request("GET", "/v1/context")
    except TurumbaAuthError as e:
        error(str(e))
        raise typer.Exit(1) from None

    if output == "json":
        render_json(context)
        return

    if not isinstance(context, dict):
        render_json(context)
        return

    accounts = context.get("accounts", [])
    roles = context.get("roles", [])

    console.print("\n[bold]Your Turumba Context[/bold]\n")

    if accounts:
        console.print(f"  [bold]Accounts[/bold] ({len(accounts)}):")
        for acc in accounts:
            name = acc.get("name", "unnamed")
            acc_id = acc.get("id", "")
            active = "[green]active[/green]" if acc.get("is_active") else "[red]inactive[/red]"
            console.print(f"    • {name} ({acc_id}) — {active}")

    if roles:
        console.print(f"\n  [bold]Roles[/bold] ({len(roles)}):")
        for role in roles:
            name = role.get("name", "unnamed")
            role_id = role.get("id", "")
            console.print(f"    • {name} ({role_id})")

    console.print()
