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

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

from __future__ import annotations

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


def _get_guide_path() -> str:
    """Resolve the path to amplitude-ai.md shipped with the package.

    Checks two locations in order:
    1. Development layout: three directories up from this file
    2. Wheel install layout: sibling of the amplitude_ai package in site-packages
    """
    dev_candidate = Path(__file__).resolve().parent.parent.parent / "amplitude-ai.md"
    if dev_candidate.exists():
        return str(dev_candidate)

    try:
        pkg_dir = importlib.resources.files("amplitude_ai")
        wheel_candidate = Path(str(pkg_dir)).parent / "amplitude-ai.md"
        if wheel_candidate.exists():
            return str(wheel_candidate)
    except Exception:
        pass

    return "amplitude-ai.md"


def _print_guide() -> None:
    """Print the full contents of amplitude-ai.md to stdout."""
    guide_path = _get_guide_path()
    path = Path(guide_path)
    if path.exists():
        sys.stdout.write(path.read_text(encoding="utf-8"))
    else:
        sys.stderr.write(
            f"amplitude-ai.md not found at {guide_path}.\n"
            f"Reinstall with: pip install amplitude-ai\n"
        )
        sys.exit(1)


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

    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"
            f"  --print-guide Print the full instrumentation guide to stdout\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)

    if args[0] == "--print-guide":
        _print_guide()
        sys.exit(0)

    command = args[0]

    # Dispatch via direct Python calls to avoid PATH resolution issues
    # with editable installs and virtual environments.
    # SystemExit raised by subcommands (e.g. doctor) propagates naturally.
    # Unhandled exceptions are caught and converted to exit code 1.
    try:
        if command == "mcp":
            sys.argv = ["amplitude-ai-mcp", *args[1:]]
            from amplitude_ai.cli.mcp import main as mcp_main
            mcp_main()
        elif command == "doctor":
            sys.argv = ["amplitude-ai-doctor", *args[1:]]
            from amplitude_ai.cli.doctor import main as doctor_main
            doctor_main()
        elif command == "status":
            sys.argv = ["amplitude-ai-status", *args[1:]]
            from amplitude_ai.cli.status import main as status_main
            status_main()
        else:
            sys.stderr.write(
                f"Unknown command: {command}\n"
                f"Usage: amplitude-ai <mcp|doctor|status|--print-guide>\n"
            )
            sys.exit(1)
    except SystemExit:
        raise
    except Exception as exc:
        sys.stderr.write(f"amplitude-ai {command}: {exc}\n")
        sys.exit(1)
