"""Central MFA policy — the SINGLE source of truth for all projects.
The admin sets it (via set_mfa_policy); every project reads it (get_mfa_policy).
Persisted to policy.json so it survives restarts.
"""
import json
import os

_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), "policy.json")
_VALID = {"none", "totp", "email", "sms"}


def get_mfa_policy() -> dict:
    """Return the single active MFA method enforced for all projects."""
    try:
        with open(_FILE) as f:
            method = json.load(f).get("method", "email")
    except (FileNotFoundError, ValueError):
        method = os.getenv("MFA_METHOD", "email")
    return {"method": method}


def set_mfa_policy(method: str) -> dict:
    """Admin sets THE active MFA method (totp | email | sms | none)."""
    method = (method or "none").lower()
    if method not in _VALID:
        return {"ok": False, "error": f"invalid method '{method}'"}
    with open(_FILE, "w") as f:
        json.dump({"method": method}, f)
    return {"ok": True, "method": method}
