"""quark login — authenticate and store JWT token."""
import typer
from rich.console import Console
from rich.prompt import Prompt

from quark import config, client

console = Console()


def run(
    email: str = typer.Option("", "--email", "-e", help="Account email"),
    token: str = typer.Option("", "--token", "-t", help="Provide token directly"),
):
    """Authenticate with Quark-AI and save your token."""
    if token:
        cfg = {}
        try:
            cfg = config.load()
        except FileNotFoundError:
            pass
        cfg["token"] = token
        config.save(cfg)
        console.print("[bold green]✓[/bold green] Token saved to .quark/config.toml")
        return

    if not email:
        email = Prompt.ask("Email")
    password = Prompt.ask("Password", password=True)

    with console.status("Authenticating…"):
        try:
            data = client.login(email, password)
        except client.QuarkError as e:
            console.print(f"[bold red]✗[/bold red] {e.detail}")
            raise typer.Exit(1)

    tok = data.get("access_token") or data.get("token")
    if not tok:
        console.print("[bold red]✗[/bold red] Unexpected response — no token returned.")
        raise typer.Exit(1)

    cfg = {}
    try:
        cfg = config.load()
    except FileNotFoundError:
        pass
    cfg["token"] = tok
    config.save(cfg)

    plan = data.get("plan", "")
    console.print(
        f"[bold green]✓[/bold green] Logged in as [bold]{email}[/bold]"
        + (f"  [dim]({plan})[/dim]" if plan else "")
    )
