"""Per-username login rate limiter (in-memory, per-process)."""

from __future__ import annotations

import time
from threading import Lock

WINDOW_SECONDS = 300
MAX_FAILS = 5

_FAILS: dict[str, list[float]] = {}
_LOCK = Lock()


def check(username: str) -> int:
    """Return retry-after seconds, or 0 if allowed."""
    now = time.monotonic()
    with _LOCK:
        fails = [t for t in _FAILS.get(username, []) if now - t < WINDOW_SECONDS]
        _FAILS[username] = fails
        if len(fails) >= MAX_FAILS:
            return int(WINDOW_SECONDS - (now - fails[0]))
    return 0


def record_failure(username: str) -> None:
    now = time.monotonic()
    with _LOCK:
        _FAILS.setdefault(username, []).append(now)


def reset(username: str) -> None:
    with _LOCK:
        _FAILS.pop(username, None)