"""Environment switching commands (for development)."""

from typing import Annotated

import typer

from paracord.utils.console import (
    console,
    print_header,
    print_success,
    print_error,
    print_warning,
    print_info,
)
from paracord.auth.config import (
    get_current_environment,
    get_authenticated_orgs,
    set_current_environment,
    get_config,
    get_user_email,
    get_org_for_path,
    get_org_credentials,
)
from pathlib import Path

auth_app = typer.Typer(
    name="auth",
    help="Authentication utilities (environment switching).",
    no_args_is_help=True,
    hidden=True,  # Hide from main help since it's for dev use
)


@auth_app.command(name="status")
def status() -> None:
    """Show current authentication status."""
    env = get_current_environment()
    config = get_config()
    orgs = get_authenticated_orgs(env)
    user_email = get_user_email()
    cwd = Path.cwd()
    current_org_id = get_org_for_path(cwd)

    print_header("Auth Status")

    if env == "development":
        console.print(f"[info]Environment:[/info] {env}")
        console.print(f"[info]API URL:[/info] {config['environments'][env]['api_url']}")

    if user_email:
        console.print(f"\n[success]Logged in[/success]")
        console.print(f"  Email: {user_email}")
        console.print(f"  Organizations: {len(orgs)}")

        if current_org_id:
            org_creds = get_org_credentials(env, current_org_id)
            if org_creds:
                console.print(f"  Current org (this directory): {org_creds['name']}")
        elif len(orgs) > 1:
            console.print(f"  [warning]No org selected for this directory[/warning]")
            console.print(f"    Run [command]paracord org[/command] to select one")
    elif orgs:
        console.print(f"\n[success]Logged in[/success]")
        console.print(f"  Organizations: {len(orgs)}")
    else:
        console.print(f"\n[warning]Not logged in[/warning]")
        console.print("  Run [command]paracord login[/command] to authenticate")


@auth_app.command(name="env")
def switch_env(
    environment: Annotated[
        str,
        typer.Argument(help="Environment to switch to (development or production)"),
    ],
) -> None:
    """Switch between environments (development/production)."""
    try:
        set_current_environment(environment)
        print_success(f"Switched to {environment}")

        # Show login status for new env
        orgs = get_authenticated_orgs(environment)
        if orgs:
            print_info(f"Authenticated with {len(orgs)} organization(s)")
        else:
            print_warning("Not logged in to this environment")
    except ValueError as e:
        print_error(str(e))
        raise typer.Exit(1)
