# Copyright (c) 2025, ASM UI APP and contributors
# License: MIT

import frappe
from frappe import _


@frappe.whitelist()
def get_two_factor_status(user: str | None = None):
	"""Return whether 2FA is enabled site-wide and required for the given user (OTP App flow)."""
	target = user or frappe.session.user
	if not target or target == "Guest":
		frappe.throw(_("Not logged in"), frappe.AuthenticationError)

	from frappe.twofactor import get_verification_method, two_factor_is_enabled_for_

	enabled_globally = bool(int(frappe.db.get_single_value("System Settings", "enable_two_factor_auth") or 0))
	method = get_verification_method() if enabled_globally else None
	required_for_user = False
	if enabled_globally and target != "Administrator":
		required_for_user = bool(two_factor_is_enabled_for_(target))

	return {
		"enabled_globally": enabled_globally,
		"required_for_user": required_for_user,
		"method": method,
		"otp_app": method == "OTP App",
	}
