# -*- coding: utf-8 -*-
"""HTTP transport implementation for MCP server"""
import logging
import os
from pathlib import Path

from mcp.server.fastmcp import FastMCP

import fastmcp

from .base import BaseTransport

logger = logging.getLogger(__name__)


class HttpTransport(BaseTransport):
    """HTTP transport for MCP server communication using FastMCP's built-in Streamable HTTP support"""

    def __init__(self, app: FastMCP, host: str = "0.0.0.0", port: int = 8000):
        """
        Initialize HTTP transport

        Args:
            app: The FastMCP application instance
            host: Host to bind to
            port: Port to bind to
        """
        self.app = app
        self.host = host
        self.port = port

        # Create storage directory if IMAGE_STORAGE_DIR is configured
        storage_dir = os.environ.get("IMAGE_STORAGE_DIR")
        if storage_dir:
            Path(storage_dir).mkdir(parents=True, exist_ok=True)

    def run(self) -> None:
        """Start the HTTP server and block until complete"""
        logging.basicConfig(level=logging.INFO)
        logger.info(f"Starting HTTP server on {self.host}:{self.port}")
        logger.info(
            f"MCP Streamable HTTP endpoint: http://{self.host}:{self.port}/mcp/"
        )
        logger.info(
            f"Inspector 连接 URL (Inspector Connection URL): http://{self.host}:{self.port}/mcp/"
        )

        # Set host and port via fastmcp global settings
        fastmcp.settings.host = self.host
        fastmcp.settings.port = self.port

        # Use FastMCP's built-in Streamable HTTP support
        # Note: transport="http" is an alias for "streamable-http"
        self.app.run(transport="streamable-http")


def run_http(app: FastMCP, host: str = "0.0.0.0", port: int = 8000) -> None:
    """
    Convenience function to run HTTP transport

    Args:
        app: The FastMCP application instance
        host: Host to bind to
        port: Port to bind to
    """
    transport = HttpTransport(app, host=host, port=port)
    transport.run()
