"""Celery integration — TrackedTask base class.

Usage::

    from celery import Celery
    from kanban_analytics.integrations.celery import TrackedTask

    app = Celery('myapp')

    @app.task(base=TrackedTask, track=True)
    def send_email(user_id: str, template: str):
        ...

Automatically tracks:
- ``celery_task_started``  (on task execution start)
- ``celery_task_completed`` (on success, with duration)
- ``celery_task_failed``   (on failure, with error details)
"""

from __future__ import annotations

import time
from typing import Any


class TrackedTask:
    """Celery task base class that automatically tracks execution events.

    Set ``track = True`` on individual tasks to opt-in::

        @app.task(base=TrackedTask, track=True)
        def my_task(): ...

    This is designed to be used as a base class for Celery tasks.  It
    imports from ``celery`` at runtime so the package remains an
    optional dependency.
    """

    abstract = True
    track = False  # opt-in per task

    # These attributes are provided by Celery's Task base
    name: str
    request: Any

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        if not self.track:
            return super().__call__(*args, **kwargs)  # type: ignore[misc]

        from kanban_analytics import analytics

        start_time = time.time()
        task_name = getattr(self, "name", "unknown")
        task_id = getattr(self.request, "id", None)

        analytics.track(
            "celery_task_started",
            anonymous_id="celery_worker",
            properties={
                "task_name": task_name,
                "task_id": task_id,
            },
        )

        try:
            result = super().__call__(*args, **kwargs)  # type: ignore[misc]
            duration_ms = int((time.time() - start_time) * 1000)
            analytics.track(
                "celery_task_completed",
                anonymous_id="celery_worker",
                properties={
                    "task_name": task_name,
                    "task_id": task_id,
                    "duration_ms": duration_ms,
                },
            )
            return result
        except Exception as exc:
            duration_ms = int((time.time() - start_time) * 1000)
            analytics.track(
                "celery_task_failed",
                anonymous_id="celery_worker",
                properties={
                    "task_name": task_name,
                    "task_id": task_id,
                    "error": str(exc),
                    "error_type": type(exc).__name__,
                    "duration_ms": duration_ms,
                },
            )
            raise
