"""PIN rate limiting + change-PIN helper.

Standards: NIST SP 800-63B-4 5.2.2 (rate limiting); NIST SP 800-53 AC-7;
ISO 27001 A.5.17; OWASP ASVS V2.2.1; Rule 13 HITL; Rule 28.
"""
from datetime import timedelta
from django.utils import timezone

_MAX_FAILS = 5
_WINDOW_MIN = 15


def recent_fail_count(user):
    from discipline.models import AcademyPinAttempt
    cutoff = timezone.now() - timedelta(minutes=_WINDOW_MIN)
    return AcademyPinAttempt.objects.filter(
        user=user, ok=False, at__gte=cutoff).count()


def record_attempt(user, ok):
    from discipline.models import AcademyPinAttempt
    AcademyPinAttempt.objects.create(user=user, ok=ok)


def check_pin_rate_limited(user, pin, pin_hash):
    """Return True iff pin matches AND account is not rate-limited.
    Records the attempt. Rate limit: 5 fails / 15 min."""
    from django.contrib.auth.hashers import check_password
    if not pin_hash:
        return False
    if recent_fail_count(user) >= _MAX_FAILS:
        return False
    ok = bool(pin) and check_password(pin, pin_hash)
    record_attempt(user, ok)
    return ok


def change_pin(user, current_pin, new_pin, confirm_pin, pin_hash):
    """Validate a PIN change. Returns (ok:bool, err:str)."""
    from django.contrib.auth.hashers import check_password
    if not current_pin or not check_password(current_pin, pin_hash):
        return False, "Purana PIN ghalat."
    if not new_pin or len(new_pin) < 4 or len(new_pin) > 6 or not new_pin.isdigit():
        return False, "Naya PIN 4-6 hindson ka hona chahiye."
    if new_pin != confirm_pin:
        return False, "Naya PIN aur confirm match nahi karte."
    if new_pin == current_pin:
        return False, "Naya PIN purane se mukhtalif hona chahiye."
    return True, ""
