"""Shared Passwordless health router with optional FastAPI integration."""

from __future__ import annotations

import logging
import time
import importlib.util
import sys
from pathlib import Path
from types import SimpleNamespace
from types import ModuleType
from typing import Any, Dict, Mapping, cast


def _load_local_module(suffix: str, path: Path) -> ModuleType:
    module_name = f"{__name__}__{suffix}"
    existing = sys.modules.get(module_name)
    if isinstance(existing, ModuleType):
        return existing
    spec = importlib.util.spec_from_file_location(module_name, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load vendor module from {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


_HERE = Path(__file__).resolve()
_SRC_DIR = _HERE.parent.parent
_MODULE_DIR = _SRC_DIR / "modules" / "free" / "auth" / "passwordless"
_runtime = _load_local_module("passwordless_runtime", _MODULE_DIR / "passwordless.py")
_types = _load_local_module("passwordless_types", _MODULE_DIR / "passwordless_types.py")

describe_passwordless = getattr(_runtime, "describe_passwordless")
PasswordlessHealthSnapshot = getattr(_types, "PasswordlessHealthSnapshot")
as_dict = getattr(_types, "as_dict")

APIRouter: Any
FastAPIApp: Any
status: Any
JSONResponse: Any

try:  # pragma: no cover - FastAPI optional at import time
    from fastapi import APIRouter, Depends, FastAPI as FastAPIApp, status
    from fastapi.responses import JSONResponse
except ImportError:  # pragma: no cover - allow import without FastAPI installed
    APIRouter = cast(Any, None)
    FastAPIApp = cast(Any, None)
    JSONResponse = None
    status = SimpleNamespace(HTTP_200_OK=200, HTTP_503_SERVICE_UNAVAILABLE=503)
    _FASTAPI_AVAILABLE = False
else:
    _FASTAPI_AVAILABLE = True

logger = logging.getLogger("passwordless.health")

_STARTED_AT = time.monotonic()

if _FASTAPI_AVAILABLE:
    router = APIRouter(prefix="/api/health/module", tags=["health"])
else:  # pragma: no cover - executed only when FastAPI unavailable
    router = None


def _collect_snapshot() -> PasswordlessHealthSnapshot:
    metadata: Mapping[str, Any] = describe_passwordless()
    return PasswordlessHealthSnapshot.from_mapping(metadata)


if _FASTAPI_AVAILABLE:

    @router.get(  # type: ignore[union-attr]
        "/passwordless",
        summary="Passwordless module health check",
        status_code=status.HTTP_200_OK,
    )
    async def passwordless_health_check(  # pragma: no cover - exercised in integration tests
        snapshot: PasswordlessHealthSnapshot = Depends(_collect_snapshot),
    ) -> Dict[str, Any]:
        payload: Dict[str, Any] = as_dict(snapshot)
        payload.update({"status": "ok"})
        payload.setdefault("module", "passwordless")
        payload.setdefault("version", "{{ rapidkit_vendor_version }}")
        payload.setdefault("uptime", max(0.0, time.monotonic() - _STARTED_AT))
        logger.debug("Passwordless health payload generated", extra={"payload": payload})
        return payload

else:  # pragma: no cover - executed only without FastAPI

    async def passwordless_health_check() -> Dict[str, Any]:  # type: ignore[override]
        raise RuntimeError("FastAPI must be installed to expose Passwordless health endpoints")


def register_passwordless_health(app: Any) -> None:
    """Attach the shared Passwordless health router to a FastAPI app."""

    if not _FASTAPI_AVAILABLE:
        raise RuntimeError("FastAPI must be installed to register Passwordless health routes")
    if FastAPIApp is not None and not isinstance(app, FastAPIApp):  # pragma: no cover
        raise TypeError("register_passwordless_health expects a FastAPI application instance")
    if router is None:  # pragma: no cover - defensive guard
        raise RuntimeError("Passwordless health router unavailable")

    app.include_router(router)


__all__ = ["passwordless_health_check", "register_passwordless_health", "router"]
