# file: integrations/sqlalchemy.py

import time
import uuid
from datetime import datetime, timezone

from ..apiTelemetry import TelemetryClient, get_trace_id, spans_var


def setup(engine, client: TelemetryClient):
    """
    Attaches event listeners to a SQLAlchemy Engine for performance monitoring.

    This function registers 'before_cursor_execute' and 'after_cursor_execute'
    hooks. These hooks will automatically create 'db.query' spans for any
    SQL query executed, provided that a trace is already active (e.g., within
    a Flask request or a `trace_transaction` context).

    Args:
        engine: The SQLAlchemy Engine instance to instrument.
        client (TelemetryClient): The active telemetry client instance (currently
                                 unused here but kept for API consistency).
    """
    # Imported lazily so that importing this integration module never crashes
    # when SQLAlchemy is not installed (shared hosting / minimal setups).
    from sqlalchemy import event  # type: ignore[import-not-found]

    def before_cursor_execute(
        conn, cursor, statement, parameters, context, executemany
    ):
        """
        Event listener fired just before a DB cursor executes a query.

        This function checks if a telemetry trace is currently active by looking
        at the `spans_var` context variable. If a trace is active, it records
        a high-precision start time in the `conn.info` dictionary. `conn.info` is a
        standard, thread-safe SQLAlchemy feature for passing state through an
        execution event chain.
        """
        # Only start the timer if we are inside an active trace context.
        if spans_var.get() is not None:
            conn.info["telemetry_start_time"] = time.perf_counter()

    def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        """
        Event listener fired just after a DB cursor has finished a query.

        If a 'telemetry_start_time' was recorded by the 'before' listener, this
        function calculates the query duration, formats the query data into a
        'db.query' span, and appends it to the list of active spans in `spans_var`.
        """
        # Retrieve the start time from the connection's info dictionary.
        start_time = conn.info.pop("telemetry_start_time", None)

        if start_time is not None:
            # As a safeguard, get the active span list from the context variable.
            active_spans = spans_var.get()

            # If the context was cleared between 'before' and 'after', do nothing.
            if active_spans is None:
                return

            # Calculate the duration in milliseconds.
            duration_ms = (time.perf_counter() - start_time) * 1000

            # Create a precise start timestamp for the span.
            start_dt = datetime.fromtimestamp(
                time.time() - (duration_ms / 1000), tz=timezone.utc
            )

            try:
                duration_ms_int = int(duration_ms)
            except (TypeError, ValueError):
                duration_ms_int = 0

            # Construct the span payload.
            db_span = {
                "span_id": str(uuid.uuid4()),
                "trace_id": get_trace_id(),
                "type": "db.query",
                "message": statement.strip(),  # The raw SQL statement.
                "duration_ms": duration_ms_int,
                "start_timestamp": start_dt.isoformat(),
                "attributes": {
                    "db.system": engine.name,
                    "db.name": conn.engine.url.database,
                },
            }

            # Append the newly created span to the active trace's span list.
            active_spans.append(db_span)

    # Explicitly register the listener functions with the engine.
    # This is more robust than using decorators within a setup function.
    event.listen(engine, "before_cursor_execute", before_cursor_execute)  # type: ignore[attr-defined]
    event.listen(engine, "after_cursor_execute", after_cursor_execute)  # type: ignore[attr-defined]
