# file: integrations/pymongo.py

"""
PyMongo Instrumentation Module.

Uses PyMongo's Command Monitoring API to create trace spans for MongoDB commands.

### Cara Penggunaan (PENTING)
Berbeda dengan monkey patching, instrumentasi pymongo memerlukan Anda untuk secara manual menerapkan listener ini saat Anda membuat koneksi ke MongoDB.

Impor telemetry_listener yang sudah dibuat oleh init_telemetry() dan teruskan ke MongoClient.

Contoh:

from pymongo import MongoClient
# Impor listener yang sudah diinisialisasi
from your_library.integrations.pymongo import telemetry_listener

# --- Buat daftar listener ---
# Cek apakah listener berhasil dibuat (telemetri aktif dan pymongo terinstal)
listeners = [telemetry_listener] if telemetry_listener else []

# --- Terapkan listener saat membuat MongoClient ---
# SEBELUM:
# client = MongoClient('mongodb://localhost:27017/')

# SESUDAH:
client = MongoClient('mongodb://localhost:27017/', event_listeners=listeners)

# --- Penggunaan selanjutnya tetap sama ---
db = client.my_database
result = db.my_collection.find_one({"name": "test"}) # <-- Operasi ini akan otomatis dilacak
"""

import time
from datetime import datetime, timezone

from ..apiTelemetry import logger, record_span, spans_var

# Global flag and variable to hold the listener instance.
_instrumented = False
telemetry_listener = None

# A dictionary to store start times, keyed by the command's request_id.
_start_times = {}


def instrument():
    """
    Initializes the MongoCommandListener. This does not perform monkey patching.
    The user must manually apply the listener to their MongoClient instance.
    """
    global _instrumented, telemetry_listener
    if _instrumented:
        return

    try:
        from pymongo import monitoring  # type: ignore[import-not-found]
    except ImportError:
        logger.debug("'pymongo' library not found, skipping instrumentation.")
        return

    class MongoCommandListener(monitoring.CommandListener):
        """A PyMongo listener that creates trace spans from command events."""

        def started(self, event):
            """Called before a command is sent to the server."""
            # Only start the timer if we are inside an active trace context.
            if spans_var.get() is not None:
                _start_times[event.request_id] = time.perf_counter()

        def _create_span(self, event, has_error=False):
            """Record a span for a completed Mongo command.

            Uses ``record_span`` with the already-measured duration. The old
            implementation re-timed the operation with ``time.sleep(duration)``
            inside a ``trace_span`` block — which made the calling thread sleep
            for the full query duration a SECOND time (double latency).
            """
            if event.request_id in _start_times:
                start_time = _start_times.pop(event.request_id)
                duration_ms = (time.perf_counter() - start_time) * 1000
                start_dt = datetime.fromtimestamp(
                    time.time() - (duration_ms / 1000), tz=timezone.utc
                )

                # Only the command name and collection are recorded — never the
                # full command document (may contain sensitive data).
                collection = event.command.get(event.command_name)
                sanitized_command = f"{event.command_name} on '{collection}'"

                record_span(
                    f"MONGODB {event.command_name.upper()}",
                    duration_ms,
                    start_timestamp=start_dt.isoformat(),
                    attributes={
                        "db.system": "mongodb",
                        "db.statement": sanitized_command,
                        "db.collection": collection,
                        "db.name": event.database_name,
                        "has_error": has_error,
                    },
                    span_type="db.query",
                )

        def succeeded(self, event):
            """Called after a command succeeds."""
            self._create_span(event, has_error=False)

        def failed(self, event):
            """Called after a command fails."""
            self._create_span(event, has_error=True)

    telemetry_listener = MongoCommandListener()
    _instrumented = True
    # logger.info("PyMongo CommandListener initialized. Apply it manually to your MongoClient.")
