"""Simple per-user rate limit using Django's cache backend (Redis in prod)."""
from __future__ import annotations

import time

from django.core.cache import cache

from apps.core.dashboard.role_groups import is_admin


WINDOW_SECONDS = 3600
DEFAULT_LIMIT = 30


def check_and_consume(user, *, limit: int = DEFAULT_LIMIT, window_s: int = WINDOW_SECONDS) -> bool:
    """Return True when the user has budget left, False when rate-limited.

    Admins bypass — they need the bot for ops/support and won't abuse it.
    """
    if is_admin(user):
        return True
    bucket = int(time.time() // window_s)
    key = f"assistant:rl:{user.pk}:{bucket}"
    if cache.add(key, 1, window_s):
        return True
    try:
        n = cache.incr(key)
    except ValueError:
        # Key disappeared between add and incr; treat as fresh.
        cache.set(key, 1, window_s)
        return True
    return n <= limit
