"""API throttling aligned with PRD Table 65 (per-minute client budgets)."""

from rest_framework.throttling import SimpleRateThrottle


class JWTObtainPairThrottle(SimpleRateThrottle):
    """Stricter cap on token issuance (integration + abuse resistance)."""

    scope = "jwt_obtain"


class RepApiClientThrottle(SimpleRateThrottle):
    """Per-client throttle for machine-to-machine REP API usage."""

    scope = "rep_api_client"

    def get_cache_key(self, request, view):
        client = getattr(request, "rep_api_client", None)
        if client is None:
            ident = self.get_ident(request)
            return self.cache_format % {"scope": self.scope, "ident": ident}
        return self.cache_format % {"scope": self.scope, "ident": f"rep-client-{client.pk}"}


class RepCompletionCallbackThrottle(SimpleRateThrottle):
    """Dedicated throttle for SCORM/LTI completion callbacks."""

    scope = "rep_completion_callback"

    def get_cache_key(self, request, view):
        client = getattr(request, "rep_api_client", None)
        if client is None:
            ident = self.get_ident(request)
            return self.cache_format % {"scope": self.scope, "ident": ident}
        return self.cache_format % {"scope": self.scope, "ident": f"rep-callback-{client.pk}"}
