"""OAuth CLI commands for subscription authentication."""

from pathlib import Path
from typing import Optional

import typer
from rich.console import Console

oauth_app = typer.Typer(help="Manage OAuth authentication for subscription-based providers")
console = Console()


@oauth_app.command("login")
def login(
    provider: str = typer.Argument("anthropic", help="Provider name"),
    token: Optional[str] = typer.Option(None, "--token", "-t", help="OAuth token (from claude setup-token)"),
):
    """Login to a provider using OAuth.

    For Anthropic Claude Max/Pro, run 'claude setup-token' and paste the token here.

    Example:
        nanobot oauth login anthropic --token sk-ant-oat01-xxx
    """
    from nanobot.config.oauth_store import OAuthStore
    from nanobot.config.schema import OAuthCredentials

    if provider != "anthropic":
        console.print(f"[red]OAuth login for {provider} not yet supported[/red]")
        return

    if not token:
        console.print("Please provide your OAuth token:")
        console.print("  1. Run: claude setup-token")
        console.print("  2. Copy the sk-ant-oat01-... token")
        console.print("  3. Run: nanobot oauth login anthropic --token <your-token>")
        console.print()
        token = typer.prompt("Token", hide_input=True)

    if not token or "sk-ant-oat" not in token:
        console.print("[red]Invalid token. Must contain sk-ant-oat[/red]")
        return

    store = OAuthStore(Path.home() / ".nanobot")
    creds = OAuthCredentials(
        access_token=token,
        token_type="token"  # setup-token doesn't expire
    )
    store.save(provider, creds)

    console.print(f"[green]Successfully saved {provider} OAuth credentials![/green]")


@oauth_app.command("status")
def status():
    """Show OAuth credential status."""
    from nanobot.config.oauth_store import OAuthStore

    store = OAuthStore(Path.home() / ".nanobot")

    providers = ["anthropic"]
    found_any = False

    for provider in providers:
        creds = store.load(provider)
        if creds:
            found_any = True
            st = "valid"
            if creds.is_expired:
                st = "EXPIRED"
            elif creds.expires_soon:
                st = "expires soon"

            token_preview = creds.access_token[:20] + "..."
            console.print(f"  {provider}: {token_preview} ({st})")

    if not found_any:
        console.print("No OAuth credentials configured.")
        console.print("Run: nanobot oauth login anthropic --token <token>")


@oauth_app.command("logout")
def logout(
    provider: str = typer.Argument("anthropic", help="Provider name"),
):
    """Remove OAuth credentials for a provider."""
    from nanobot.config.oauth_store import OAuthStore

    store = OAuthStore(Path.home() / ".nanobot")
    if store.delete(provider):
        console.print(f"[green]Removed {provider} OAuth credentials[/green]")
    else:
        console.print(f"No credentials found for {provider}")
