from typing import Optional

from starlette.requests import Request

from authx_core.middleware._stats import _stats as authxStats

TIMER_ATTRIBUTE = "__authx_timer__"


def _record(request: Request, note: Optional[str] = None) -> None:
    """
    Call this function at any point that you want to display elapsed time during the handling of a single request

    This can help profile which piece of a request is causing a performance bottleneck.

    Note that for this function to succeed, the request should have been generated by a FastAPI app
    that has had timing middleware added using the `authx_core.authxMiddleware` function.
    """
    timer = getattr(request.state, TIMER_ATTRIBUTE, None)
    if timer is not None:
        assert isinstance(timer, authxStats)
        timer.emit(note)
    else:
        raise ValueError("No timer present on request")
