"""
Authentication commands for Amina CLI.

Commands:
    amina auth set-key <key>  - Store an API key
    amina auth status         - Check authentication status
    amina auth logout         - Clear stored credentials
    amina auth session <id>   - Link outputs to a web conversation
"""

import typer
from rich.console import Console
from rich.panel import Panel

from amina_cli.auth import (
    set_api_key,
    get_credentials,
    clear_credentials,
    get_key_display,
    is_authenticated,
    set_session_id,
    get_session_id,
    AuthError,
    API_KEY_PREFIX,
    CREDENTIALS_FILE,
)

app = typer.Typer(no_args_is_help=True)
console = Console()


@app.command("set-key")
def set_key(
    key: str = typer.Argument(
        ...,
        help=f"Your API key (starts with '{API_KEY_PREFIX}')",
    ),
):
    """
    Store an API key for authentication.

    Get an API key at: https://app.aminoanalytica.com/settings/api

    The key is stored locally in ~/.amina/credentials.json.
    Validation happens server-side when the key is used.

    Example:
        amina auth set-key "ami_7f3k9x2m..."
    """
    try:
        set_api_key(key)
        console.print(
            Panel(
                f"[green]API key saved successfully![/green]\n\n"
                f"Key: {get_key_display(key)}\n"
                f"Location: {CREDENTIALS_FILE}",
                title="Authentication",
                border_style="green",
            )
        )
        console.print("\nYou can now run tools with: [bold]amina run <tool>[/bold]")

    except ValueError as e:
        console.print(f"[red]Error:[/red] {e}")
        console.print(f"\nAPI keys should look like: [dim]{API_KEY_PREFIX}7f3k9x2m4p5n6j8h...[/dim]")
        console.print("Get one at: https://app.aminoanalytica.com/settings/api")
        raise typer.Exit(1)


@app.command()
def status():
    """
    Check current authentication status.

    Shows whether you're authenticated and displays the key prefix.
    """
    if not is_authenticated():
        console.print(
            Panel(
                "[yellow]Not authenticated[/yellow]\n\n"
                "Run: [bold]amina auth set-key <your_api_key>[/bold]\n\n"
                "Get an API key at: https://app.aminoanalytica.com/settings/api",
                title="Authentication Status",
                border_style="yellow",
            )
        )
        raise typer.Exit(1)

    try:
        creds = get_credentials()
        key_display = get_key_display(creds["api_key"])
        session_id = get_session_id()

        status_lines = [
            "[green]Authenticated[/green]",
            "",
            f"API Key: {key_display}",
            f"Config: {CREDENTIALS_FILE}",
        ]

        if session_id:
            status_lines.append(f"Linked session: {session_id[:8]}...")

        console.print(
            Panel(
                "\n".join(status_lines),
                title="Authentication Status",
                border_style="green",
            )
        )

    except AuthError as e:
        console.print(f"[red]Error:[/red] {e}")
        raise typer.Exit(1)


@app.command()
def logout():
    """
    Clear stored credentials.

    Removes the API key from ~/.amina/credentials.json.
    You'll need to set a new key to use the CLI again.
    """
    if not is_authenticated():
        console.print("[yellow]Already logged out.[/yellow]")
        return

    clear_credentials()
    console.print("[green]Credentials cleared successfully.[/green]")
    console.print(f"Removed: {CREDENTIALS_FILE}")


@app.command()
def session(
    session_id: str = typer.Argument(
        None,
        help="Web conversation ID to link outputs to",
    ),
    unlink: bool = typer.Option(
        False,
        "--unlink",
        "-u",
        help="Remove the session link",
    ),
):
    """
    Link CLI outputs to a web conversation.

    When linked, your CLI tool outputs will appear in the
    specified web conversation's artifact panel.

    Example:
        amina auth session abc123-def456
        amina auth session --unlink
    """
    if unlink:
        try:
            set_session_id(None)
            console.print("[green]Session link removed.[/green]")
        except AuthError as e:
            console.print(f"[red]Error:[/red] {e}")
            raise typer.Exit(1)
        return

    if not session_id:
        current = get_session_id()
        if current:
            console.print(f"Currently linked to session: {current}")
        else:
            console.print("No session linked. Provide a session ID to link.")
            console.print("\nUsage: amina auth session <conversation_id>")
        return

    try:
        set_session_id(session_id)
        console.print(f"[green]Linked to session:[/green] {session_id}")
        console.print("CLI outputs will now appear in your web conversation.")
    except AuthError as e:
        console.print(f"[red]Error:[/red] {e}")
        raise typer.Exit(1)
