from __future__ import annotations

import json
import os
import sys
from pathlib import Path
from typing import Any

from amplitude_ai.cli.doctor import PROVIDER_PACKAGES
from amplitude_ai.core.tracking import SDK_VERSION


def _detect_installed_providers() -> list[dict[str, Any]]:
    """Check which provider packages are importable."""
    import_map: dict[str, str] = {
        "openai": "openai",
        "anthropic": "anthropic",
        "google-genai": "google.generativeai",
        "mistralai": "mistralai",
        "boto3": "boto3",
    }
    results: list[dict[str, Any]] = []
    for pkg in PROVIDER_PACKAGES:
        module_name = import_map.get(pkg, pkg)
        try:
            __import__(module_name)
            results.append({"name": pkg, "installed": True})
        except ImportError:
            results.append({"name": pkg, "installed": False})
    return results


def run_status() -> dict[str, Any]:
    providers = _detect_installed_providers()
    env: dict[str, bool] = {
        "AMPLITUDE_AI_API_KEY": bool(os.environ.get("AMPLITUDE_AI_API_KEY")),
        "AMPLITUDE_AI_CONTENT_MODE": bool(os.environ.get("AMPLITUDE_AI_CONTENT_MODE")),
        "AMPLITUDE_AI_DEBUG": bool(os.environ.get("AMPLITUDE_AI_DEBUG")),
    }
    return {
        "version": SDK_VERSION,
        "providers": providers,
        "env": env,
    }


def main() -> None:
    json_mode = "--json" in sys.argv[1:]
    result = run_status()

    if json_mode:
        print(json.dumps(result, indent=2))
    else:
        print(f"amplitude-ai v{result['version']}\n")
        print("Providers:")
        for p in result["providers"]:
            mark = "\u2713" if p["installed"] else "\u2717"
            print(f"  {mark} {p['name']}")
        print("\nEnvironment:")
        for key, present in result["env"].items():
            mark = "\u2713" if present else "\u2717"
            print(f"  {mark} {key}")
        print()
