"""Paste endpoint rate limiting for /api/portal/teacher/paste/.

Standards:
  OWASP ASVS 5.0 V11.1.4 (rate limiting)
  NIST SP 800-53 AC-7 (unsuccessful logon attempts)
  NIST SP 800-63B-4 s5.2.2 (authentication throttling)
  ISO 27001:2022 A.8.20 (network security - abuse prevention)
  Rule 24 (sandbox first); Rule 28 (standards supremacy)

Policy:
  30 successful POSTs / 60 min per teacher user (rolling window)
  On exceed: HTTP 429 + Roman-Urdu message + audit log line.
  Counter stored in Django cache; per-user key.
"""
import json
import time
from pathlib import Path as _Path

from django.core.cache import cache
from django.http import HttpResponse

PROTECTED_PATH_PREFIX = "/api/portal/teacher/paste/"
LIMIT_PER_HOUR = 30
WINDOW_SECONDS = 3600
AUDIT_PATH = _Path("/home/orkoworo/idealogy/tmp/paste_rate_limit.jsonl")


class PasteRateLimitMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            resp = self._check(request)
            if resp is not None:
                return resp
        except Exception:
            # Fail-open on internal error — this is abuse prevention,
            # not an authentication boundary.
            pass
        return self.get_response(request)

    def _check(self, request):
        if request.method != "POST":
            return None
        if not request.path.startswith(PROTECTED_PATH_PREFIX):
            return None
        user = getattr(request, "user", None)
        if not user or not user.is_authenticated:
            return None
        key = "paste_rl:" + str(user.id)
        now = int(time.time())
        bucket = cache.get(key) or []
        bucket = [t for t in bucket if now - t < WINDOW_SECONDS]
        if len(bucket) >= LIMIT_PER_HOUR:
            self._log(user, "BLOCKED", len(bucket))
            return HttpResponse(
                "Bohat zyada paste koshishein. Barah-e-karam ek ghante baad koshish karein.",
                status=429,
                content_type="text/plain; charset=utf-8",
            )
        bucket.append(now)
        cache.set(key, bucket, WINDOW_SECONDS + 60)
        return None

    @staticmethod
    def _log(user, outcome, count):
        try:
            AUDIT_PATH.parent.mkdir(parents=True, exist_ok=True)
            with AUDIT_PATH.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps({
                    "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                    "user": getattr(user, "username", "?"),
                    "outcome": outcome,
                    "count": count,
                    "limit": LIMIT_PER_HOUR,
                    "window_seconds": WINDOW_SECONDS,
                }) + "\n")
        except Exception:
            pass
