"""GPAI CLI - AI-powered problem solver."""

import typer
from rich.console import Console

from gpai_cli.config import save_config, load_config, get_token

app = typer.Typer(
    name="gpai",
    help="GPAI CLI - AI-powered problem solver",
    no_args_is_help=True,
)
console = Console()


@app.command()
def login(
    api_key: str | None = typer.Option(None, "--api-key", help="GPAI API key (gpai_sk_...)"),
    token: str | None = typer.Option(None, "--token", help="JWT token (legacy)"),
    api_url: str | None = typer.Option(None, "--api-url", help="Custom API URL"),
) -> None:
    """Login with your GPAI API key."""
    if not api_key and not token:
        api_key = typer.prompt("Enter your GPAI API key", hide_input=True)

    config = load_config()
    config["token"] = api_key or token
    if api_url:
        config["api_url"] = api_url
    save_config(config)
    console.print("[green]Logged in successfully.[/green]")


@app.command()
def whoami() -> None:
    """Show current login status."""
    token = get_token()
    if token:
        masked = token[:10] + "..." + token[-4:]
        console.print(f"Logged in (token: {masked})")
    else:
        console.print("[yellow]Not logged in. Run: gpai login[/yellow]")


@app.command()
def solve(
    image: str = typer.Argument(help="Path to problem image"),
    output_json: bool = typer.Option(False, "--json", help="Output as JSON"),
    output_file: str | None = typer.Option(None, "-o", "--output", help="Save to file"),
    debug: bool = typer.Option(False, "--debug", help="Show raw API response"),
) -> None:
    """Solve a math/science problem from an image."""
    from gpai_cli.commands.solve import solve as _solve

    _solve(image, output_json, output_file, debug)


@app.command()
def mcp() -> None:
    """Start GPAI MCP server for AI agent integration."""
    from gpai_cli.mcp_server import main as mcp_main

    mcp_main()


if __name__ == "__main__":
    app()
