"""TOTP helpers for authenticator apps (RFC 6238 via pyotp)."""

from __future__ import annotations

import base64
import io

import pyotp
import qrcode
from django.conf import settings


def new_secret() -> str:
    return pyotp.random_base32()


def provisioning_uri(secret: str, account_email: str) -> str:
    issuer = getattr(settings, "MFA_TOTP_ISSUER", "RUFORUM IILMP")
    return pyotp.TOTP(secret).provisioning_uri(name=account_email, issuer_name=issuer)


def verify_totp(secret: str, code: str, *, valid_window: int = 1) -> bool:
    if not secret or not code:
        return False
    normalized = code.strip().replace(" ", "")
    if not normalized.isdigit() or len(normalized) != 6:
        return False
    return pyotp.TOTP(secret).verify(normalized, valid_window=valid_window)


def qr_code_data_uri(otpauth_uri: str) -> str:
    """PNG data URI for embedding in <img src>."""
    img = qrcode.make(otpauth_uri, box_size=4, border=2)
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    return f"data:image/png;base64,{b64}"
