"""
FastAPI integration for LaneSwap client.

This module provides automatic integration with FastAPI applications,
registering the /health endpoint with async support.
"""

from typing import TYPE_CHECKING, Any, Dict

if TYPE_CHECKING:
    from ..core import LaneSwap


def setup_fastapi_integration(app: Any, laneswap: "LaneSwap") -> None:
    """
    Setup FastAPI integration for LaneSwap.

    Automatically registers:
    - GET /health endpoint (with async support)
    - Lifespan shutdown handler integration

    Args:
        app: FastAPI application instance
        laneswap: LaneSwap instance

    Examples:
        >>> from fastapi import FastAPI
        >>> from laneswap import LaneSwap
        >>> app = FastAPI()
        >>> laneswap = LaneSwap(app)  # Auto-calls setup_fastapi_integration
    """
    try:
        from fastapi import FastAPI
        from fastapi.responses import JSONResponse
    except ImportError:
        raise ImportError(
            "FastAPI is required for FastAPI integration. "
            "Install with: pip install laneswap-client[fastapi]"
        )

    if not isinstance(app, FastAPI):
        raise TypeError(f"Expected FastAPI app, got {type(app)}")

    # Register /health endpoint
    @app.get("/health")
    async def health() -> JSONResponse:
        """Health check endpoint for LaneSwap Monitor."""
        from ..health import build_health_response

        try:
            # Run synchronous health checks
            sync_checks = laneswap.health_registry.run_checks()

            # Run async health checks if any are registered
            async_checks: Dict[str, Any] = {}
            if laneswap.health_registry.has_async_checks():
                async_checks = await laneswap.health_registry.run_async_checks()

            # Merge all checks
            custom_checks = {**sync_checks, **async_checks} if (sync_checks or async_checks) else None

            # Build response
            response = build_health_response(
                service_name=laneswap.service_name,
                custom_checks=custom_checks,
                status="healthy",
            )

            return JSONResponse(content=response, status_code=200)

        except Exception as e:
            # Health check failed
            response = build_health_response(
                service_name=laneswap.service_name,
                custom_checks={"error": str(e)},
                status="unhealthy",
            )
            return JSONResponse(content=response, status_code=503)

    # Note: Shutdown handlers are managed by signal handlers
    # FastAPI's lifespan events don't reliably handle SIGTERM
    # so we rely on the signal handlers registered in core.py
