# file: integrations/celery.py

"""
Celery Instrumentation Module.

This module uses Celery signals to enable distributed tracing. It instruments
both the task producer (e.g., a web app) and the task consumer (the Celery worker).

### How To
In Celery Worker:
    also call init_telemetry() in the file where Celery worker is started.
    This will install the consumer_prerun and consumer_postrun listeners.
    When the worker executes a task, it will create a new "TASK" trace but use the same trace_id.
"""

import time
from datetime import datetime, timezone

from ..apiTelemetry import (
    TRACE_ID_HEADER,
    get_current_client,
    get_trace_id,
    inject_trace_id,
    logger,
    spans_var,
    trace_id_var,
    trace_span,
)

_instrumented = False


def instrument():
    """Connects the telemetry handlers to the Celery signals."""
    global _instrumented
    if _instrumented:
        return

    try:
        # Imported lazily so the integration module itself never crashes at
        # import time when celery is not installed.
        from celery import signals  # type: ignore[import-not-found]
    except ImportError:
        logger.debug("'celery' library not found, skipping instrumentation.")
        return

    signals.before_task_publish.connect(producer_before_publish)
    signals.task_prerun.connect(consumer_prerun)
    signals.task_postrun.connect(consumer_postrun)

    _instrumented = True


def producer_before_publish(sender=None, headers=None, body=None, **kwargs):
    """
    Signal handler executed on the producer side before a task is sent.
    Injects the current trace_id into the task headers and creates a
    'PRODUCE' span.
    """
    trace_id = get_trace_id()
    if trace_id and headers is not None:
        # Propagate via the standard header (the consumer still accepts the
        # legacy "telemetry_trace_id" key for older peers).
        inject_trace_id(headers)

        task_name = sender or "unknown_task"
        span_name = f"CELERY PRODUCE {task_name}"

        with trace_span(span_name, attributes={"task.name": task_name}):
            pass  # The context manager handles span creation and timing.


def _coerce_duration_ms(duration_ms: float) -> int:
    """Never let a malformed duration crash a worker callback."""
    try:
        return int(duration_ms)
    except (TypeError, ValueError):
        return 0


def consumer_prerun(sender=None, task_id=None, task=None, **kwargs):
    """
    Signal handler executed on the consumer (worker) side before a task runs.
    Extracts the trace_id from the task headers and starts a new trace context.
    """
    if task is None:
        return

    request_meta = getattr(task, "request", None)
    headers = (
        getattr(request_meta, "headers", None) if request_meta is not None else None
    )
    # Accept the standard propagation header, with a fallback to the legacy key
    # so tasks queued by older library versions stay continuous.
    incoming_trace_id = None
    if headers:
        incoming_trace_id = headers.get(TRACE_ID_HEADER) or headers.get(
            "telemetry_trace_id"
        )
    if incoming_trace_id:
        # Reuse the trace_id created by the producer.
        trace_id_var.set(incoming_trace_id)
        spans_var.set([])

        # Store start time on the task object to pass it to postrun.
        task.telemetry_start_time = time.perf_counter()


def consumer_postrun(sender=None, task_id=None, task=None, state=None, **kwargs):
    """
    Signal handler executed on the consumer side after a task finishes.
    Finalizes and sends the trace for the background job execution.
    """
    if task is None:
        return

    start_time = getattr(task, "telemetry_start_time", None)
    trace_id = get_trace_id()

    # Only proceed if this task was instrumented by prerun.
    if not start_time or not trace_id:
        return

    duration_ms = (time.perf_counter() - start_time) * 1000
    collected_spans = spans_var.get() or []
    has_error = state == "FAILURE"
    task_name = getattr(task, "name", None) or "unknown_task"

    # Get the client instance to send data
    client = get_current_client()
    if not client:
        return

    end_dt = datetime.now(timezone.utc)
    start_dt = datetime.fromtimestamp(
        end_dt.timestamp() - (duration_ms / 1000), tz=timezone.utc
    )

    trace_payload = {
        "trace": {
            "id": trace_id,
            "http_method": "TASK",
            "http_path": task_name,
            "http_host": client.config.service_name,  # Use service name as host
            "http_status_code": 500 if has_error else 200,
            "duration_ms": _coerce_duration_ms(duration_ms),
            "has_error": has_error,
            "start_timestamp": start_dt.isoformat(),
            "end_timestamp": end_dt.isoformat(),
        },
        "logs_and_spans": collected_spans,
    }
    client.capture_trace(trace_payload)

    # Clean up context variables for the next task in the worker.
    trace_id_var.set(None)
    spans_var.set(None)
