"""Decorators for auditing function execution."""

from __future__ import annotations

import time
from collections.abc import Callable
from functools import wraps
from typing import TYPE_CHECKING, Any, TypeVar

if TYPE_CHECKING:
    from axm_audit.auditor import Auditor

F = TypeVar("F", bound=Callable[..., Any])


def audit_track(
    name: str | None = None,
    auditor: Auditor | None = None,
) -> Callable[[F], F]:
    """Decorator to track function execution time.

    Args:
        name: Custom name for the function. Defaults to function name.
        auditor: Auditor instance to record metrics. Uses global if None.

    Example:
        >>> @audit_track(name="data_processing")
        ... def process_data(df):
        ...     return df.filter(...)
    """

    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            # Get auditor
            nonlocal auditor
            if auditor is None:
                from axm_audit import auditor as global_auditor

                auditor = global_auditor

            func_name = name or func.__name__
            start = time.perf_counter_ns()

            try:
                result = func(*args, **kwargs)
                return result
            finally:
                duration_ns = time.perf_counter_ns() - start
                auditor.on_function_call(func_name, duration_ns)

        return wrapper  # type: ignore

    return decorator
