"""
Bootstrap module for ``amplitude-ai-instrument`` CLI.

Python automatically imports a module named ``sitecustomize`` found on
``sys.path`` at interpreter startup.  The CLI wrapper prepends the
directory containing this file to ``PYTHONPATH`` and sets
``_AMPLITUDE_AI_BOOTSTRAP=1`` before ``os.execvp``-ing the user's
command.  The new Python process then picks up this file, applies
monkey-patches, and chains to any pre-existing ``sitecustomize``.

This is the same pattern used by ``ddtrace-run`` and
``opentelemetry-instrument``.
"""

from __future__ import annotations

import os
import sys


def _bootstrap() -> None:
    if os.environ.get("_AMPLITUDE_AI_BOOTSTRAP") != "1":
        return

    # Prevent re-entry if the user nests instrumented processes.
    os.environ.pop("_AMPLITUDE_AI_BOOTSTRAP", None)

    api_key = os.environ.get("AMPLITUDE_AI_API_KEY", "")
    if not api_key:
        return

    try:
        from amplitude import Amplitude

        from amplitude_ai.patching import patch

        amplitude = Amplitude(api_key)
        debug = os.environ.get("AMPLITUDE_AI_DEBUG", "").lower() == "true"

        content_mode_str = os.environ.get("AMPLITUDE_AI_CONTENT_MODE", "full").lower()
        # Pass content_mode to preserve the full/metadata_only/customer_enriched
        # distinction instead of collapsing to a boolean privacy_mode.
        patched = patch(amplitude=amplitude, debug=debug, content_mode=content_mode_str)

        if patched:
            note = ""
            if content_mode_str != "full":
                note = f" (content_mode={content_mode_str})"
            print(
                f"amplitude-ai-instrument: patched {', '.join(patched)}{note}",
                file=sys.stderr,
            )
    except Exception as exc:
        print(
            f"amplitude-ai-instrument: bootstrap error: {exc}",
            file=sys.stderr,
        )


_bootstrap()

# ------------------------------------------------------------------
# Chain to the original sitecustomize (if any) so we don't shadow it.
# Remove our bootstrap dir from sys.path first, then try to import
# the "real" sitecustomize that would have been found without us.
# ------------------------------------------------------------------

_bootstrap_dir = os.path.dirname(os.path.abspath(__file__))
if _bootstrap_dir in sys.path:
    sys.path.remove(_bootstrap_dir)

try:
    import importlib

    sys.modules.pop("sitecustomize", None)
    importlib.import_module("sitecustomize")
except ImportError:
    pass
