"""Legacy HTTP transport shim.

Prefer FastMCP native `streamable-http` transport via `TRANSPORT_TYPE=http`.
"""

from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Optional

try:
    from fastapi import FastAPI, Request
    from fastapi.responses import JSONResponse
    import uvicorn
    HAS_FASTAPI = True
except ImportError:
    HAS_FASTAPI = False

from ..errors import TransportError, ConfigurationError
from ..logging import get_logger
from .base import Transport

if TYPE_CHECKING:
    from mcp.server import Server

logger = get_logger(__name__)


class HTTPTransport(Transport):
    """HTTP/REST transport for hosted MCP deployments.
    
    Provides an HTTP API for MCP protocol, allowing remote clients to connect
    over HTTP/HTTPS. Supports authentication via JWT tokens and middleware stack.
    
    Requires FastAPI and uvicorn to be installed.
    """
    
    def __init__(
        self,
        host: str = "0.0.0.0",
        port: int = 8080,
        enable_cors: bool = True,
        cors_origins: Optional[list[str]] = None,
    ):
        """Initialize the HTTP transport.
        
        Args:
            host: Host to bind to
            port: Port to bind to
            enable_cors: Whether to enable CORS
            cors_origins: List of allowed CORS origins (default: ["*"])
            
        Raises:
            ConfigurationError: If FastAPI is not installed
        """
        if not HAS_FASTAPI:
            raise ConfigurationError(
                "FastAPI and uvicorn are required for HTTP transport. "
                "Install with: pip install fastapi uvicorn[standard]",
                setting="HTTP_TRANSPORT"
            )
        
        self.host = host
        self.port = port
        self.enable_cors = enable_cors
        self.cors_origins = cors_origins or ["*"]
        
        self.app: Optional[FastAPI] = None
        self._server_task: Optional[asyncio.Task] = None
        self._uvicorn_server: Optional[uvicorn.Server] = None
    
    async def start(self, server: Server) -> None:
        """Start the HTTP transport.
        
        Args:
            server: The MCP server instance to serve
            
        Raises:
            TransportError: If the transport fails to start
        """
        try:
            logger.info("http_transport_starting", host=self.host, port=self.port)
            
            # Create FastAPI app
            self.app = FastAPI(
                title="Meta Ads MCP Server",
                description="HTTP transport for Model Context Protocol",
                version="1.0.0"
            )
            
            # Add CORS middleware if enabled
            if self.enable_cors:
                from fastapi.middleware.cors import CORSMiddleware
                self.app.add_middleware(
                    CORSMiddleware,
                    allow_origins=self.cors_origins,
                    allow_credentials=True,
                    allow_methods=["*"],
                    allow_headers=["*"],
                )
            
            # Add health check endpoint
            @self.app.get("/health")
            async def health_check():
                return {"status": "healthy", "transport": "http"}
            
            # Add MCP protocol endpoints
            @self.app.post("/mcp/list_tools")
            async def list_tools(request: Request):
                """List available tools."""
                return JSONResponse(
                    status_code=501,
                    content={
                        "error": (
                            "This transport shim is deprecated. "
                            "Use FastMCP streamable-http transport (TRANSPORT_TYPE=http)."
                        )
                    },
                )
            
            @self.app.post("/mcp/call_tool")
            async def call_tool(request: Request):
                """Call a tool."""
                return JSONResponse(
                    status_code=501,
                    content={
                        "error": (
                            "This transport shim is deprecated. "
                            "Use FastMCP streamable-http transport (TRANSPORT_TYPE=http)."
                        )
                    },
                )
            
            # Configure uvicorn server
            config = uvicorn.Config(
                app=self.app,
                host=self.host,
                port=self.port,
                log_level="info",
                access_log=False,  # Use our structured logging instead
            )
            
            self._uvicorn_server = uvicorn.Server(config)
            
            # Start server in background task
            self._server_task = asyncio.create_task(self._uvicorn_server.serve())
            
            logger.info("http_transport_started", host=self.host, port=self.port)
            
            # Wait for server task to complete
            await self._server_task
            
        except Exception as exc:
            logger.error("http_transport_failed", error=str(exc))
            raise TransportError(
                f"Failed to start HTTP transport: {exc}",
                transport_type="http"
            ) from exc
    
    async def stop(self) -> None:
        """Stop the HTTP transport.
        
        Raises:
            TransportError: If the transport fails to stop cleanly
        """
        try:
            logger.info("http_transport_stopping")
            
            if self._uvicorn_server:
                self._uvicorn_server.should_exit = True
            
            if self._server_task and not self._server_task.done():
                self._server_task.cancel()
                try:
                    await self._server_task
                except asyncio.CancelledError:
                    pass
            
            logger.info("http_transport_stopped")
            
        except Exception as exc:
            logger.error("http_transport_stop_failed", error=str(exc))
            raise TransportError(
                f"Failed to stop HTTP transport: {exc}",
                transport_type="http"
            ) from exc
    
    @property
    def transport_type(self) -> str:
        """Get the transport type identifier.
        
        Returns:
            "http"
        """
        return "http"

