"""MFA tools — TOTP secrets, provisioning URIs, QR images and code verification."""
import base64
from io import BytesIO

import pyotp
import qrcode


def generate_mfa_secret() -> str:
    """Generate a random Base32 secret for TOTP."""
    return pyotp.random_base32()


def get_provisioning_uri(secret: str, email: str, issuer: str = "Indovision TA-ATS") -> str:
    """Create the provisioning URI used to render the authenticator QR code."""
    return pyotp.totp.TOTP(secret).provisioning_uri(name=email, issuer_name=issuer)


def get_qr_code(secret: str, email: str, issuer: str = "Indovision TA-ATS") -> str:
    """Return the authenticator QR as a base64 PNG data URI (no client lib needed).
    Reusable by any project — just put the returned string in an <img src=...>."""
    uri = pyotp.totp.TOTP(secret).provisioning_uri(name=email, issuer_name=issuer)
    img = qrcode.make(uri)
    buf = BytesIO()
    img.save(buf, format="PNG")
    return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()


def verify_mfa_code(secret: str, code: str) -> bool:
    """Verify a 6-digit TOTP code against the secret."""
    return pyotp.TOTP(secret).verify(code)
