"""Client for auth_mcp — standalone Auth service (password + MFA) on port 9000.
TA-ATS delegates login + MFA to it. Thread-safe: fresh connection per call.
"""
import asyncio

from django.conf import settings

try:
    from fastmcp import Client
except ImportError:
    Client = None


class MCPServiceError(Exception):
    """Raised when auth_mcp is unreachable or a tool call fails."""


def call_tool(name, arguments):
    if Client is None:
        raise MCPServiceError("fastmcp Client not available - install fastmcp package")
    
    async def _run():
        async with Client(settings.MCP_URL) as c:
            result = await c.call_tool(name, arguments)
            return result.data
    try:
        return asyncio.run(_run())
    except Exception as e:
        raise MCPServiceError(f"auth_mcp unavailable: {e}") from e


# ---- login (credentials) — auth_mcp checks the Django-style hash ----
def verify_login(email, password) -> dict:
    """Returns {'verified': bool, 'role': str}."""
    return call_tool("verify_login", {"email": email, "password": password})


def sync_user(email, password_hash, role="ADMIN") -> bool:
    """Push a Django password hash to auth_mcp (so it can verify logins)."""
    return bool(call_tool("sync_user", {"email": email, "password_hash": password_hash, "role": role}))


def delete_user(email) -> bool:
    return bool(call_tool("delete_user", {"email": email}))


# ---- MFA (auth_mcp stores enrollment in mfa_users, keyed by user_key=email) ----
def mfa_setup(user_key, email) -> dict:
    return call_tool("mfa_setup", {"user_key": user_key, "email": email})


def mfa_send_login_otp(user_key, email) -> dict:
    return call_tool("mfa_send_login_otp", {"user_key": user_key, "email": email})


def mfa_verify(user_key, code) -> bool:
    return bool(call_tool("mfa_verify", {"user_key": user_key, "code": code}))


def mfa_status(user_key) -> dict:
    return call_tool("mfa_status", {"user_key": user_key})


# ---- stateless email OTP (MCP generates + emails, returns the code to store locally) ----
def send_email_otp(email) -> dict:
    """Returns {'otp': str, 'sent': bool}. Caller stores the OTP and verifies later."""
    return call_tool("send_email_otp", {"email": email})


# ---- policy ----
_cached_mfa_policy = None


def get_mfa_policy() -> dict:
    global _cached_mfa_policy
    if _cached_mfa_policy is None:
        _cached_mfa_policy = call_tool("get_mfa_policy", {})
    return _cached_mfa_policy


def set_mfa_policy(method) -> dict:
    global _cached_mfa_policy
    res = call_tool("set_mfa_policy", {"method": method})
    _cached_mfa_policy = res
    return res
