import secrets
from fastapi import Request

OTP_CODE_KEY = "otp_code"
OTP_VERIFIED_KEY = "otp_verified"

def start_otp(request: Request) -> str:
    # 6-digit numeric code
    code = str(secrets.randbelow(900000) + 100000)
    request.session[OTP_CODE_KEY] = code
    request.session[OTP_VERIFIED_KEY] = False
    return code

def verify_otp(request: Request, code: str) -> bool:
    expected = request.session.get(OTP_CODE_KEY)
    if expected and code and code.strip() == expected:
        request.session[OTP_VERIFIED_KEY] = True
        request.session.pop(OTP_CODE_KEY, None)
        return True
    return False

def is_otp_verified(request: Request) -> bool:
    return bool(request.session.get(OTP_VERIFIED_KEY))
