"""
Flask integration for LaneSwap client.

This module provides automatic integration with Flask applications,
registering the /health endpoint and shutdown handlers.
"""

from typing import TYPE_CHECKING, Any, Tuple

if TYPE_CHECKING:
    from ..core import LaneSwap


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

    Automatically registers:
    - GET /health endpoint
    - Shutdown handler integration

    Args:
        app: Flask application instance
        laneswap: LaneSwap instance

    Examples:
        >>> from flask import Flask
        >>> from laneswap import LaneSwap
        >>> app = Flask(__name__)
        >>> laneswap = LaneSwap(app)  # Auto-calls setup_flask_integration
    """
    from flask import Flask, jsonify

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

    # Register /health endpoint
    @app.route("/health", methods=["GET"])
    def health() -> Tuple[Any, int]:
        """Health check endpoint for LaneSwap Monitor."""
        from ..health import build_health_response

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

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

            return jsonify(response), 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 jsonify(response), 503

    # Register shutdown handler
    @app.teardown_appcontext
    def shutdown_handler(exception: Any = None) -> None:
        """Execute LaneSwap shutdown handlers on app teardown."""
        # This is called when app context is torn down
        # Signal handlers will handle actual shutdown
        pass
