"""
=========================================
CV6 AI Trading OS
Shared in-memory login rate limiter — max 5 attempts per IP per 60s.
Shared across /auth/login and /users/login so an attacker can't bypass
the limit by alternating between the two login endpoints.
=========================================
"""

import time
from collections import defaultdict
from fastapi import HTTPException

_login_attempts: dict = defaultdict(list)   # ip -> [timestamps]
_RATE_LIMIT = 5          # max attempts
_RATE_WINDOW = 60.0      # seconds


def check_login_rate_limit(ip: str) -> None:
    now = time.time()
    attempts = _login_attempts[ip]
    _login_attempts[ip] = [t for t in attempts if now - t < _RATE_WINDOW]
    if len(_login_attempts[ip]) >= _RATE_LIMIT:
        raise HTTPException(
            status_code=429,
            detail=f"Too many login attempts. Try again in {_RATE_WINDOW:.0f}s."
        )
    _login_attempts[ip].append(now)
