"""Auth commands — login, logout, register, verify-email, status."""

from __future__ import annotations

import time

from rich.prompt import Prompt
import typer

from turumba_cli.client import TurumbaClient
from turumba_cli.config import get_value, set_value
from turumba_cli.credentials import TokenSet, delete_tokens, load_tokens, save_tokens
from turumba_cli.errors import TurumbaAPIError
from turumba_cli.output import console, error, info, success

app = typer.Typer(name="auth", help="Authentication -- login, logout, register, status.")


@app.command()
def login(
    email: str = typer.Option(None, "--email", "-e", help="Email address"),
    password: str = typer.Option(None, "--password", "-p", help="Password"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Authenticate with Turumba and store tokens."""
    if not email:
        email = Prompt.ask("[bold]Email[/bold]")
    if not password:
        password = Prompt.ask("[bold]Password[/bold]", password=True)

    client = TurumbaClient(gateway_url=gateway_url)

    try:
        response = client.post(
            "/v1/auth/login",
            data={"email": email, "password": password},
            auth=False,
        )
    except TurumbaAPIError as e:
        error(str(e))
        raise typer.Exit(1) from None

    tokens = TokenSet.from_login_response(response, email=email)
    save_tokens(tokens)
    success(f"Logged in as [bold]{email}[/bold]")

    if response.get("account_created"):
        info("A new account was created for you.")

    try:
        context = client.request("GET", "/v1/context")
        accounts = context.get("accounts", []) if isinstance(context, dict) else []
        if accounts:
            info(f"You have access to {len(accounts)} account(s):")
            for acc in accounts:
                name = acc.get("name", acc.get("id", "unknown"))
                acc_id = acc.get("id", "")
                console.print(f"  - {name} ({acc_id})")

            if len(accounts) == 1:
                set_value("default_account_id", accounts[0]["id"])
                info(f"Default account set to: {accounts[0].get('name', accounts[0]['id'])}")
    except Exception:
        pass


@app.command()
def logout() -> None:
    """Clear stored authentication tokens."""
    delete_tokens()
    success("Logged out. Tokens cleared.")


@app.command()
def status() -> None:
    """Show current authentication status."""
    tokens = load_tokens()
    if tokens is None:
        error("Not authenticated. Run: turumba auth login")
        raise typer.Exit(1)

    console.print(f"  [bold]Email[/bold]: {tokens.email or 'unknown'}")
    if tokens.is_expired:
        console.print("  [bold]Status[/bold]: [red]Expired[/red]")
        console.print("  Run [bold]turumba auth login[/bold] to re-authenticate.")
    else:
        console.print("  [bold]Status[/bold]: [green]Active[/green]")
        remaining = int(tokens.expires_at - time.time())
        minutes = remaining // 60
        console.print(f"  [bold]Expires in[/bold]: {minutes} minutes")

    account_id = get_value("default_account_id")
    if account_id:
        console.print(f"  [bold]Default account[/bold]: {account_id}")


@app.command()
def register(
    email: str = typer.Option(None, "--email", "-e", help="Email address"),
    password: str = typer.Option(None, "--password", "-p", help="Password"),
    given_name: str = typer.Option(None, "--given-name", help="First name"),
    family_name: str = typer.Option(None, "--family-name", help="Last name"),
    account_name: str = typer.Option(None, "--account-name", help="Organization name"),
    phone: str = typer.Option(None, "--phone", help="Phone number"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Register a new Turumba account."""
    if not email:
        email = Prompt.ask("[bold]Email[/bold]")
    if not password:
        password = Prompt.ask("[bold]Password[/bold]", password=True)
    if not given_name:
        given_name = Prompt.ask("[bold]First name[/bold]")
    if not family_name:
        family_name = Prompt.ask("[bold]Last name[/bold]")
    if not account_name:
        account_name = Prompt.ask("[bold]Organization name[/bold]")

    client = TurumbaClient(gateway_url=gateway_url)

    data = {
        "email": email,
        "password": password,
        "given_name": given_name,
        "family_name": family_name,
        "account_name": account_name,
    }
    if phone:
        data["phone"] = phone

    try:
        response = client.post("/v1/auth/register", data=data, auth=False)
    except TurumbaAPIError as e:
        error(str(e))
        raise typer.Exit(1) from None

    message = (
        response.get("message", "Registration successful")
        if isinstance(response, dict)
        else str(response)
    )
    success(message)
    info("Check your email for a verification code, then run: turumba auth verify-email")


@app.command("verify-email")
def verify_email(
    email: str = typer.Option(None, "--email", "-e", help="Email address"),
    code: str = typer.Option(None, "--code", "-c", help="Verification code"),
    account_name: str = typer.Option(None, "--account-name", help="Organization name"),
    phone: str = typer.Option(None, "--phone", help="Phone number"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Verify your email with the confirmation code."""
    if not email:
        email = Prompt.ask("[bold]Email[/bold]")
    if not code:
        code = Prompt.ask("[bold]Verification code[/bold]")

    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {"email": email, "confirmation_code": code}
    if account_name:
        data["account_name"] = account_name
    if phone:
        data["phone"] = phone

    try:
        response = client.post("/v1/auth/verify-email", data=data, auth=False)
    except TurumbaAPIError as e:
        error(str(e))
        raise typer.Exit(1) from None

    success("Email verified successfully!")
    if isinstance(response, dict):
        account = response.get("account", {})
        if account:
            info(f"Account created: {account.get('name', '')} ({account.get('id', '')})")
    info("You can now log in: turumba auth login")
