"""In-memory brute-force rate limiter."""
import threading
import time
from collections import defaultdict


# â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
# Brute-force protection (in-memory rate limiter)
# â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
class _RateLimiter:
    """Simple in-memory rate limiter with progressive lockout."""

    def __init__(self):
        self._attempts = defaultdict(list)
        self._lockouts = {}
        self._lock = threading.Lock()

    def is_locked(self, key, lockout_secs=900):
        """Returns True if key is currently in lockout."""
        with self._lock:
            if key in self._lockouts:
                if time.time() < self._lockouts[key]:
                    return True
                del self._lockouts[key]
            return False

    def record_failure(self, key, max_attempts=5, lockout_secs=900):
        """Record a failed attempt. Returns seconds until lockout clears (0 if not locked)."""
        now = time.time()
        with self._lock:
            self._attempts[key] = [t for t in self._attempts[key] if now - t < lockout_secs]
            self._attempts[key].append(now)
            if len(self._attempts[key]) >= max_attempts:
                self._lockouts[key] = now + lockout_secs
                self._attempts[key] = []
                return lockout_secs
        return 0

    def clear(self, key):
        with self._lock:
            self._attempts.pop(key, None)
            self._lockouts.pop(key, None)


_login_limiter = _RateLimiter()
