"""
Built-in HTTP server for framework-free LaneSwap integration.

This module provides a simple HTTP server for services that don't
use a web framework like Flask or FastAPI.
"""

import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import TYPE_CHECKING, Any, Optional

from .health import build_health_response

if TYPE_CHECKING:
    from .core import LaneSwap


class HealthHTTPRequestHandler(BaseHTTPRequestHandler):
    """
    HTTP request handler for /health endpoint.

    This handler serves health check requests for vanilla
    (framework-free) LaneSwap integrations.
    """

    # Class variable to store LaneSwap instance
    laneswap_instance: Optional["LaneSwap"] = None

    def do_GET(self) -> None:
        """Handle GET requests."""
        if self.path == "/health":
            self._handle_health_check()
        else:
            self._send_404()

    def _handle_health_check(self) -> None:
        """Handle /health endpoint request."""
        if self.laneswap_instance is None:
            self._send_error_response("LaneSwap instance not configured", 500)
            return

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

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

            # Send JSON response
            self._send_json_response(response, 200)

        except Exception as e:
            self._send_error_response(f"Health check failed: {str(e)}", 500)

    def _send_json_response(self, data: Any, status_code: int = 200) -> None:
        """
        Send JSON response.

        Args:
            data: Data to serialize as JSON
            status_code: HTTP status code
        """
        self.send_response(status_code)
        self.send_header("Content-Type", "application/json")
        self.end_headers()

        response_bytes = json.dumps(data).encode("utf-8")
        self.wfile.write(response_bytes)

    def _send_error_response(self, message: str, status_code: int) -> None:
        """
        Send error response.

        Args:
            message: Error message
            status_code: HTTP status code
        """
        self._send_json_response({"error": message, "status": "unhealthy"}, status_code)

    def _send_404(self) -> None:
        """Send 404 Not Found response."""
        self._send_error_response("Endpoint not found", 404)

    def log_message(self, format: str, *args: Any) -> None:
        """
        Override to suppress default HTTP server logs.

        The LaneSwap logger will handle logging instead.
        """
        # Suppress default logging - LaneSwap handles it
        pass


def start_health_server(laneswap: "LaneSwap") -> threading.Thread:
    """
    Start HTTP server for health checks in a background thread.

    Args:
        laneswap: LaneSwap instance

    Returns:
        Thread running the HTTP server

    Examples:
        >>> laneswap = LaneSwap()
        >>> server_thread = start_health_server(laneswap)
        >>> # Server now running in background
        >>> server_thread.join()  # Wait for shutdown
    """
    # Set class variable so handler can access LaneSwap instance
    HealthHTTPRequestHandler.laneswap_instance = laneswap

    # Create HTTP server
    server = HTTPServer(("0.0.0.0", laneswap.port), HealthHTTPRequestHandler)

    # Run server in background thread
    def run_server() -> None:
        """Run the HTTP server until shutdown."""
        try:
            while laneswap.running:
                server.handle_request()
        except Exception as e:
            laneswap._logger.error(f"Health server error: {e}")
        finally:
            server.server_close()

    thread = threading.Thread(target=run_server, daemon=True)
    thread.start()

    return thread
