"""
Climeter CLI helper commands.

Usage:
    climeter init      — prompt for API key, write to .env
    climeter status    — show config + buffered event count
    climeter diagnose  — check config and test API connection
    climeter version   — show SDK version
"""

import json
import os
import sys
from pathlib import Path
from typing import List, Optional

from .client import ClimeterClient, DEFAULT_BASE_URL
from .meter import Meter

# ANSI colours
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
BOLD = "\033[1m"
RESET = "\033[0m"


# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------

def cmd_init() -> int:
    """Prompt for API key and write to .env in the current directory."""
    print(f"{BOLD}Climeter — initial setup{RESET}\n")
    print("Get your API key at https://climeter.auvh.ai\n")

    # Check if already set
    existing = os.environ.get("CLIMETER_API_KEY", "")
    if existing:
        masked = existing[:8] + "..." + existing[-4:] if len(existing) > 12 else "***"
        print(f"{YELLOW}Note:{RESET} CLIMETER_API_KEY is already set in the environment ({masked}).")
        overwrite = input("Overwrite? [y/N]: ").strip().lower()
        if overwrite != "y":
            print("Aborted.")
            return 0

    api_key = input("Enter your Climeter API key (clm_xxx): ").strip()
    if not api_key:
        print(f"{RED}Error:{RESET} API key cannot be empty.", file=sys.stderr)
        return 1

    # Write to .env
    env_path = Path(".env")
    lines: List[str] = []

    if env_path.exists():
        with open(env_path) as f:
            lines = [l for l in f.readlines() if not l.startswith("CLIMETER_API_KEY=")]

    lines.append(f"CLIMETER_API_KEY={api_key}\n")

    with open(env_path, "w") as f:
        f.writelines(lines)

    print(f"\n{GREEN}✓{RESET} API key written to {env_path.resolve()}")
    print(f"  Add to your shell: {BOLD}export CLIMETER_API_KEY={api_key[:8]}...{RESET}")
    return 0


def cmd_status() -> int:
    """Show current config and buffered event count."""
    print(f"{BOLD}Climeter Status{RESET}\n")

    api_key = os.environ.get("CLIMETER_API_KEY", "")
    api_url = os.environ.get("CLIMETER_API_URL", DEFAULT_BASE_URL)
    tool_slug = os.environ.get("CLIMETER_TOOL_SLUG", "(not set)")

    if api_key:
        masked = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 12 else "***"
        print(f"{GREEN}✓{RESET} API key:    {masked}")
    else:
        print(f"{RED}✗{RESET} API key:    not set  (export CLIMETER_API_KEY=clm_xxx)")

    print(f"  API URL:    {api_url}")
    print(f"  Tool slug:  {tool_slug}")

    # Show .env if present
    env_path = Path(".env")
    if env_path.exists():
        print(f"\n  .env found at {env_path.resolve()}")

    return 0 if api_key else 1


def cmd_diagnose() -> int:
    """Full diagnostics: check config and test API connectivity."""
    print(f"{BOLD}Climeter Diagnostics{RESET}\n")

    api_key = os.environ.get("CLIMETER_API_KEY", "")
    api_url = os.environ.get("CLIMETER_API_URL", DEFAULT_BASE_URL)

    if not api_key:
        print(f"{RED}✗{RESET} CLIMETER_API_KEY not set")
        print("  Run: climeter init")
        return 1

    masked = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 12 else "***"
    print(f"{GREEN}✓{RESET} API key: {masked}")
    print(f"  API URL: {api_url}")

    # Test connection
    print(f"\n{BOLD}Testing connection…{RESET}")
    client = ClimeterClient(api_key=api_key, base_url=api_url, flush_interval=0.1)
    client.enqueue({
        "tool_slug": "_diagnostic",
        "event_name": "ping",
        "price_usd": 0.0,
        "metadata": {},
        "timestamp": "",
    })

    import time
    time.sleep(0.5)
    client.flush()
    time.sleep(0.5)
    buffered = client.buffered_count
    client.shutdown()

    if buffered == 0:
        print(f"{GREEN}✓{RESET} Connection test successful")
    else:
        print(f"{YELLOW}⚠{RESET}  Ping buffered (API may be unreachable). Will retry automatically.")

    return 0


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------

def main(argv: Optional[List[str]] = None) -> int:
    argv = argv or sys.argv[1:]

    if not argv:
        print(f"{BOLD}Climeter CLI{RESET}")
        print("  init       — set up API key")
        print("  status     — show current config")
        print("  diagnose   — check config and test connection")
        print("  version    — show SDK version")
        return 0

    cmd = argv[0]

    if cmd == "init":
        return cmd_init()
    elif cmd == "status":
        return cmd_status()
    elif cmd == "diagnose":
        return cmd_diagnose()
    elif cmd == "version":
        from . import __version__
        print(f"climeter {__version__}")
        return 0
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        print("Available: init, status, diagnose, version", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
