"""
AgniPod SDK — Command-Line Interface
=======================================

Available commands::

    agnipod login          Save your API key locally
    agnipod logout         Remove saved credentials
    agnipod status         Show current auth configuration
    agnipod models         List available models
    agnipod version        Print SDK version
"""

from __future__ import annotations

import sys
import os
import getpass
import json
import textwrap

from ._config import (
    VERSION,
    BASE_URL,
    CREDENTIALS_FILE,
    ENV_API_KEY,
    resolve_api_key,
    save_api_key,
    clear_saved_key,
)


# ── Colour helpers (no deps) ────────────────────────────────────────────

def _supports_colour() -> bool:
    """Check if the terminal supports colour output."""
    if os.environ.get("NO_COLOR"):
        return False
    if not hasattr(sys.stdout, "isatty"):
        return False
    return sys.stdout.isatty()

_COLOUR = _supports_colour()

def _green(s: str) -> str:
    return f"\033[32m{s}\033[0m" if _COLOUR else s

def _yellow(s: str) -> str:
    return f"\033[33m{s}\033[0m" if _COLOUR else s

def _red(s: str) -> str:
    return f"\033[31m{s}\033[0m" if _COLOUR else s

def _bold(s: str) -> str:
    return f"\033[1m{s}\033[0m" if _COLOUR else s

def _dim(s: str) -> str:
    return f"\033[2m{s}\033[0m" if _COLOUR else s


# ── Commands ─────────────────────────────────────────────────────────────

def cmd_login(args: list[str]) -> int:
    """Save API key to ~/.agnipod/credentials."""
    print()
    print(f"  {_bold('AgniPod Login')}")
    print(f"  {_dim('─' * 40)}")
    print()

    # Check if user passed key as an argument
    api_key = None
    if args:
        api_key = args[0]

    if not api_key:
        print(f"  Enter your API key {_dim('(starts with agni_)')}")
        print(f"  Get yours at {_dim('https://console.agnipod.com/keys')}")
        print()
        try:
            api_key = getpass.getpass("  API Key: ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            print(f"\n  {_yellow('Cancelled.')}")
            return 1

    # Sanitize: strip whitespace and surrounding quotes
    api_key = api_key.strip().strip('"').strip("'").strip()

    if not api_key:
        print(f"\n  {_red('✗')} No API key provided.")
        return 1

    if not api_key.startswith("agni_"):
        print(f"\n  {_red('✗')} Invalid key format. Keys must start with 'agni_'.")
        return 1

    path = save_api_key(api_key)

    # Mask the key for display
    masked = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 16 else api_key[:8] + "..."

    print()
    print(f"  {_green('✓')} API key saved to {path}")
    print(f"  {_dim(f'Key: {masked}')}")
    print()
    print(f"  You can now use the SDK without passing the key explicitly:")
    print(f"  {_dim('from agnipod import AgniPod; client = AgniPod()')}")
    print()
    return 0


def cmd_logout(args: list[str]) -> int:
    """Remove saved credentials."""
    if clear_saved_key():
        print(f"\n  {_green('✓')} Credentials removed.\n")
    else:
        print(f"\n  {_yellow('!')} No saved credentials found.\n")
    return 0


def cmd_status(args: list[str]) -> int:
    """Show current auth configuration."""
    print()
    print(f"  {_bold('AgniPod Status')}")
    print(f"  {_dim('─' * 40)}")
    print()

    # Check each source
    env_key = os.environ.get(ENV_API_KEY)
    saved_key = None
    try:
        if CREDENTIALS_FILE.is_file():
            text = CREDENTIALS_FILE.read_text().strip()
            if text.startswith("{"):
                data = json.loads(text)
                saved_key = data.get("api_key")
            elif text.startswith("agni_"):
                saved_key = text
    except Exception:
        pass

    active_key = resolve_api_key()
    # Determine active source
    if env_key:
        source = "AGNIPOD_API_KEY env var"
    elif saved_key:
        source = f"~/.agnipod/credentials"
    else:
        source = None

    if active_key:
        masked = active_key[:8] + "..." + active_key[-4:] if len(active_key) > 16 else active_key[:8] + "..."
        print(f"  API Key:    {_green(masked)}")
        print(f"  Source:     {source}")
    else:
        print(f"  API Key:    {_red('Not configured')}")
        print(f"  Run {_bold('agnipod login')} to set up your API key.")

    print(f"  API URL:    {BASE_URL}")
    print(f"  SDK:        agnipod v{VERSION}")
    print()

    # Show all sources
    print(f"  {_dim('Key sources (in priority order):')}")
    print(f"    1. AgniPod(api_key=...)       {_dim('(explicit)')}")
    print(f"    2. AGNIPOD_API_KEY env var    {'  ' + _green('✓ set') if env_key else '  ' + _dim('not set')}")
    print(f"    3. ~/.agnipod/credentials    {'  ' + _green('✓ saved') if saved_key else '  ' + _dim('not saved')}")
    print()
    return 0


def cmd_models(args: list[str]) -> int:
    """List available models."""
    api_key = resolve_api_key()
    if not api_key:
        print(f"\n  {_red('✗')} No API key configured. Run {_bold('agnipod login')} first.\n")
        return 1

    try:
        from .main import AgniPod
        client = AgniPod(api_key=api_key)
        model_list = client.models.list()

        print()
        print(f"  {_bold('Available Models')}")
        print(f"  {_dim('─' * 50)}")
        print()

        if not model_list.data:
            print(f"  {_dim('No models available.')}")
        else:
            for m in model_list.data:
                owned = m.get("owned_by", "")
                print(f"  {_green('•')} {m.id:<30} {_dim(owned)}")

        print()
        client.close()
        return 0

    except Exception as e:
        print(f"\n  {_red('✗')} {e}\n")
        return 1


def cmd_version(args: list[str]) -> int:
    """Print SDK version."""
    print(f"agnipod v{VERSION}")
    return 0


# ── Help ─────────────────────────────────────────────────────────────────

USAGE = textwrap.dedent("""\
    {bold}AgniPod CLI{reset} v{version}

    {bold}Usage:{reset}
      agnipod <command> [options]
      python -m agnipod <command> [options]   (use this on Windows)

    {bold}Commands:{reset}
      login          Save your API key locally (~/.agnipod/credentials)
      logout         Remove saved credentials
      status         Show current authentication configuration
      models         List available models
      version        Print SDK version

    {bold}Authentication:{reset}
      1. Run: agnipod login   (or: python -m agnipod login)
      2. Or set: export AGNIPOD_API_KEY="agni_..."
      3. Or pass: AgniPod(api_key="agni_...")

    {bold}Quick start:{reset}
      $ agnipod login
      $ python -c "from agnipod import chat; print(chat('Hello!', model='qwen3:8b'))"

    {bold}Windows:{reset}
      If 'agnipod' is not recognized, use: python -m agnipod <command>

    {bold}Documentation:{reset}
      https://docs.agnipod.com
""")


def cmd_help(args: list[str]) -> int:
    bold = "\033[1m" if _COLOUR else ""
    reset = "\033[0m" if _COLOUR else ""
    print(USAGE.format(bold=bold, reset=reset, version=VERSION))
    return 0


# ── Entry point ──────────────────────────────────────────────────────────

COMMANDS = {
    "login": cmd_login,
    "logout": cmd_logout,
    "status": cmd_status,
    "models": cmd_models,
    "version": cmd_version,
    "help": cmd_help,
    "--help": cmd_help,
    "-h": cmd_help,
    "--version": cmd_version,
    "-v": cmd_version,
}


def main():
    """CLI entry point."""
    argv = sys.argv[1:]

    if not argv:
        cmd_help([])
        sys.exit(0)

    command = argv[0].lower()
    handler = COMMANDS.get(command)

    if handler is None:
        print(f"\n  {_red('✗')} Unknown command: {command}")
        print(f"  Run {_bold('agnipod help')} for usage.\n")
        sys.exit(1)

    code = handler(argv[1:])
    sys.exit(code)


if __name__ == "__main__":
    main()
