"""Context management using contextvars for async-safe context propagation."""

from contextvars import ContextVar
from typing import Any

_fenra_context: ContextVar[dict[str, Any]] = ContextVar("fenra_context", default={})


def set_context(**kwargs: Any) -> None:
    """
    Merge new metadata into the current context.

    This function is additive. Each call merges new keys into the existing
    context dictionary. Later calls with the same key will overwrite.

    Example middleware stacking:
        # Auth middleware
        fenra.set_context(billable_customer_id="acme-corp", user_id="u_123")

        # Feature middleware (adds to existing context)
        fenra.set_context(feature="chat-assistant", environment="production")

        # Final context: {billable_customer_id, user_id, feature, environment}
    """
    current = _fenra_context.get().copy()
    current.update(kwargs)
    _fenra_context.set(current)


def get_context() -> dict[str, Any]:
    """
    Get the full merged context dictionary.

    Returns a copy to prevent external mutation.
    Called by auto-instrumentation to include in logging payload.
    """
    return _fenra_context.get().copy()


def clear_context() -> None:
    """Reset context to empty dict. Useful at request boundaries."""
    _fenra_context.set({})
