"""Main CLI entry point for amplitude-ai.

Prints the instrumentation prompt for AI coding agents and dispatches
subcommands (mcp, doctor, status).
"""

from __future__ import annotations

import importlib.metadata
import importlib.resources
import subprocess
import sys
from pathlib import Path


def _get_guide_path() -> str:
    """Resolve the path to amplitude-ai.md shipped with the package."""
    try:
        pkg_dir = importlib.resources.files("amplitude_ai")
        candidate = Path(str(pkg_dir)).parent / "amplitude-ai.md"
        if candidate.exists():
            return str(candidate)
    except Exception:
        pass
    return "amplitude-ai.md"


def main() -> None:
    args = sys.argv[1:]

    subcommands = {
        "mcp": "amplitude-ai-mcp",
        "doctor": "amplitude-ai-doctor",
        "status": "amplitude-ai-status",
    }

    if not args or args[0] in ("--help", "-h"):
        version = importlib.metadata.version("amplitude-ai")
        guide_path = _get_guide_path()
        sys.stdout.write(
            f"amplitude-ai v{version}\n"
            f"\n"
            f"Paste this into your AI coding agent (Cursor, Claude Code, Windsurf, Copilot, etc.):\n"
            f"\n"
            f"  Instrument this app with amplitude-ai. Follow {guide_path}\n"
            f"\n"
            f"CLI commands:\n"
            f"  mcp       Start the MCP server (optional, for advanced tooling)\n"
            f"  doctor    Validate environment, deps, and event pipeline\n"
            f"  status    Show SDK version, installed providers, and env config\n"
        )
        sys.exit(0)

    if args[0] in ("--version", "-v"):
        version = importlib.metadata.version("amplitude-ai")
        sys.stdout.write(f"{version}\n")
        sys.exit(0)

    command = args[0]
    if command in subcommands:
        result = subprocess.run(
            [subcommands[command], *args[1:]],
            check=False,
        )
        sys.exit(result.returncode)

    sys.stderr.write(f"Unknown command: {command}\nUsage: amplitude-ai <mcp|doctor|status>\n")
    sys.exit(1)
