# otp_utils.py
import hmac, random
from datetime import timedelta
from django.utils import timezone
from django.contrib.auth.hashers import make_password, check_password

OTP_EXPIRY_MINUTES = 10
OTP_MAX_ATTEMPTS_PER_CODE = 5
OTP_MAX_GLOBAL_FAILURES = 20

RESEND_MIN_WAIT_SECONDS = 60
RESEND_MAX_PER_HOUR = 5
RESEND_MAX_PER_DAY = 10

def default_expiry(minutes=OTP_EXPIRY_MINUTES):
    return timezone.now() + timedelta(minutes=minutes)

def fmt_ts(dt):
    return dt.astimezone().isoformat()

def generate_otp():
    return f"{random.randint(0, 999999):06d}"

def hash_otp(plain: str) -> str:
    return make_password(plain)

def matches_code(submitted: str, stored: str) -> bool:
    if check_password(submitted, stored):
        return True
    return hmac.compare_digest((submitted or ""), (stored or ""))
