"""Analytics event tracking decorator.

Provides the @{{ decorator_name }} decorator for automatic event tracking
on service methods and route handlers.

⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
"""

from __future__ import annotations

import functools
import logging
import time
from typing import Any, Callable

logger = logging.getLogger("{{ project_name }}.analytics")


def {{ decorator_name }}(
    event_name: str,
    category: str = "custom",
    *,
    include_result: bool = False,
    include_args: bool = False,
) -> Callable:
    """Decorator that tracks an analytics event when a function is called.

    Usage:
        @{{ decorator_name }}("user_created", category="crud")
        async def create_user(db, data):
            ...

        @{{ decorator_name }}("report_generated", include_result=True)
        async def generate_report(db, params):
            ...

    Args:
        event_name: Name of the event to track.
        category: Event category for grouping.
        include_result: If True, include the return value in event properties.
        include_args: If True, include function arguments in event properties.
    """

    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
            start_time = time.monotonic()
            error_occurred = False
            result = None

            try:
                result = await func(*args, **kwargs)
                return result
            except Exception:
                error_occurred = True
                raise
            finally:
                duration_ms = (time.monotonic() - start_time) * 1000
                properties: dict[str, Any] = {
                    "duration_ms": round(duration_ms, 2),
                    "success": not error_occurred,
                }

                if include_args and kwargs:
                    # Only include serializable kwargs, skip db sessions etc.
                    safe_kwargs = {
                        k: v
                        for k, v in kwargs.items()
                        if isinstance(v, (str, int, float, bool, type(None)))
                    }
                    properties["args"] = safe_kwargs

                if include_result and result is not None and not error_occurred:
                    properties["has_result"] = True

                try:
                    from {{ project_name }}.analytics.service import record_event

                    await record_event(
                        event_name=event_name,
                        category=category,
                        properties=properties,
                    )
                except Exception:
                    logger.debug("Failed to record analytics event: %s", event_name)

        @functools.wraps(func)
        def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
            start_time = time.monotonic()
            error_occurred = False

            try:
                result = func(*args, **kwargs)
                return result
            except Exception:
                error_occurred = True
                raise
            finally:
                duration_ms = (time.monotonic() - start_time) * 1000
                logger.debug(
                    "Event: %s | category=%s | duration=%.2fms | success=%s",
                    event_name,
                    category,
                    duration_ms,
                    not error_occurred,
                )

        import asyncio

        if asyncio.iscoroutinefunction(func):
            return async_wrapper
        return sync_wrapper

    return decorator
