"""
CLI wrapper for zero-code LLM instrumentation.

Usage::

    AMPLITUDE_AI_API_KEY=xxx amplitude-ai-instrument python app.py

Environment variables:

- ``AMPLITUDE_AI_API_KEY`` (required): Amplitude API key.
- ``AMPLITUDE_AI_AUTO_PATCH``: Must be ``"true"`` to enable auto-patching.
- ``AMPLITUDE_AI_CONTENT_MODE``: ``"full"`` (default), ``"metadata_only"``,
  or ``"customer_enriched"``.
- ``AMPLITUDE_AI_DEBUG``: ``"true"`` for colored stderr output.

Patching happens inside the child process via a ``sitecustomize``
bootstrap module, so patches survive the ``os.execvp`` boundary.
This is the same approach used by ``ddtrace-run`` and
``opentelemetry-instrument``.
"""

from __future__ import annotations

import os
import sys


def main() -> None:
    """Entry point for the ``amplitude-ai-instrument`` CLI."""
    api_key = os.environ.get("AMPLITUDE_AI_API_KEY", "")
    auto_patch = os.environ.get("AMPLITUDE_AI_AUTO_PATCH", "").lower() == "true"

    if not api_key:
        print(
            "amplitude-ai-instrument: AMPLITUDE_AI_API_KEY not set, passing through.",
            file=sys.stderr,
        )
    elif not auto_patch:
        print(
            "amplitude-ai-instrument: AMPLITUDE_AI_AUTO_PATCH is not 'true', passing through.",
            file=sys.stderr,
        )

    if api_key and auto_patch:
        # Signal the bootstrap sitecustomize to activate in the child process.
        os.environ["_AMPLITUDE_AI_BOOTSTRAP"] = "1"

        # Prepend our bootstrap directory to PYTHONPATH so the child
        # Python interpreter finds our sitecustomize.py at startup.
        bootstrap_dir = os.path.join(os.path.dirname(__file__), "bootstrap")
        existing_path = os.environ.get("PYTHONPATH", "")
        if existing_path:
            os.environ["PYTHONPATH"] = f"{bootstrap_dir}{os.pathsep}{existing_path}"
        else:
            os.environ["PYTHONPATH"] = bootstrap_dir

    # Execute the user's command
    args = sys.argv[1:]
    if not args:
        print("Usage: amplitude-ai-instrument <command> [args...]", file=sys.stderr)
        sys.exit(1)

    os.execvp(args[0], args)
