"""TOTP 2FA engine (Phase 7.6.4a, 2026-10-08).

Pure-stdlib implementation of RFC 6238 TOTP with RFC 4226 HOTP.
Compatible with Google Authenticator, Authy, FreeOTP, 1Password, Bitwarden.

Standards:
  RFC 6238 (TOTP)
  RFC 4226 (HOTP)
  NIST SP 800-63B AAL2 (second factor; no SMS/email)
  OWASP ASVS 5.0 V6.3 (MFA for privileged accounts)
  OWASP ASVS 5.0 V7.5.3 (re-auth before sensitive ops)
  ISO 27001 A.5.15 (access control)
  Rule 17 (feature control); Rule 18 (kill switch)

No third-party dependency. No network. No vendor.
"""
import base64
import hashlib
import hmac
import os
import secrets
import struct
import time
from urllib.parse import quote

# --- RFC 6238 defaults ------------------------------------------------
TOTP_DIGITS = 6
TOTP_PERIOD = 30        # seconds
TOTP_ALGORITHM = "sha1"  # RFC 6238 default; also accepted: sha256, sha512
VERIFY_WINDOW = 1        # accept previous/current/next 30-sec window


def generate_secret() -> str:
    """Return a fresh 20-byte Base32 secret (160 bits — NIST AAL2 minimum)."""
    raw = secrets.token_bytes(20)
    return base64.b32encode(raw).decode("ascii").rstrip("=")


def _hotp(secret_b32: str, counter: int) -> str:
    """RFC 4226 HOTP."""
    # pad base32 to correct length
    pad = (-len(secret_b32)) % 8
    padded = secret_b32 + ("=" * pad)
    key = base64.b32decode(padded, casefold=True)
    msg = struct.pack(">Q", counter)
    h = hmac.new(key, msg, getattr(hashlib, TOTP_ALGORITHM)).digest()
    offset = h[-1] & 0x0F
    binary = ((h[offset] & 0x7F) << 24 |
              (h[offset + 1] & 0xFF) << 16 |
              (h[offset + 2] & 0xFF) << 8 |
              (h[offset + 3] & 0xFF))
    code = binary % (10 ** TOTP_DIGITS)
    return str(code).zfill(TOTP_DIGITS)


def totp_now(secret_b32: str, at_time: float = None) -> str:
    """Return the current TOTP code (for tests)."""
    t = at_time if at_time is not None else time.time()
    counter = int(t // TOTP_PERIOD)
    return _hotp(secret_b32, counter)


def verify_totp(secret_b32: str, code: str,
                window: int = VERIFY_WINDOW) -> bool:
    """Constant-time TOTP verification with drift window."""
    if not secret_b32 or not code:
        return False
    code = str(code).strip()
    if len(code) != TOTP_DIGITS or not code.isdigit():
        return False
    now_counter = int(time.time() // TOTP_PERIOD)
    for offset in range(-window, window + 1):
        expected = _hotp(secret_b32, now_counter + offset)
        if hmac.compare_digest(expected, code):
            return True
    return False


def otpauth_uri(secret_b32: str, account: str,
                issuer: str = "Idealogy") -> str:
    """Return the otpauth:// URI for QR or manual entry."""
    label = quote(issuer) + ":" + quote(account)
    return ("otpauth://totp/" + label
            + "?secret=" + secret_b32
            + "&issuer=" + quote(issuer)
            + "&algorithm=SHA1&digits=" + str(TOTP_DIGITS)
            + "&period=" + str(TOTP_PERIOD))


def generate_recovery_codes(n: int = 8) -> tuple:
    """Return (plaintext_codes, sha256_hashes).

    Plaintext shown ONCE to the user; only hashes stored.
    Standards: ASVS V6.4 (single-use, time-limited recovery codes).
    """
    codes = []
    hashes = []
    for _ in range(n):
        raw = secrets.token_hex(6).upper()  # 12 hex chars
        formatted = raw[:4] + "-" + raw[4:8] + "-" + raw[8:]
        codes.append(formatted)
        hashes.append(hashlib.sha256(formatted.encode()).hexdigest())
    return codes, hashes


def check_recovery_code(user_mfa, candidate: str) -> bool:
    """Verify a recovery code. On success, remove its hash (single-use)."""
    candidate = (candidate or "").strip().upper()
    if not candidate:
        return False
    h = hashlib.sha256(candidate.encode()).hexdigest()
    hashes = list(user_mfa.recovery_hashes or [])
    if h not in hashes:
        return False
    hashes.remove(h)
    user_mfa.recovery_hashes = hashes
    user_mfa.save(update_fields=["recovery_hashes"])
    return True
