#!/usr/bin/env python3
"""
简化的调试版本 MCPStoreWiki 服务
专门用于诊断 nginx 反向代理问题
"""

from fastmcp import FastMCP
from fastmcp.server.dependencies import get_http_request, get_http_headers
from pydantic import Field
from typing import Annotated
import random
import logging
import sys
from datetime import datetime

# 配置详细日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('debug_service.log', encoding='utf-8')
    ]
)

logger = logging.getLogger(__name__)

# 创建 FastMCP 实例
mcp = FastMCP(name="DebugWeatherService")

# 简单的工具函数
@mcp.tool()
def simple_weather(city: str = Field(description="城市名称")) -> str:
    """简单的天气查询工具"""
    logger.info(f"🌤️ 简单天气查询 - 城市: {city}")
    result = f"{city}的天气：晴天，25°C"
    logger.info(f"🌤️ 返回结果: {result}")
    return result

# 添加一个诊断工具来显示HTTP请求信息
@mcp.tool()
def get_debug_info() -> str:
    """获取调试信息，包括HTTP请求详情"""
    logger.info("=" * 80)
    logger.info(f"🔍 get_debug_info 调用 - {datetime.now()}")

    info_parts = [
        "🔍 调试服务信息:",
        f"   服务名称: DebugWeatherService",
        f"   时间戳: {datetime.now().isoformat()}",
        f"   可用工具: simple_weather, get_debug_info"
    ]

    try:
        # 获取HTTP请求信息
        headers = get_http_headers()
        if headers:
            info_parts.append("\n📨 HTTP 请求头:")
            for name, value in headers.items():
                info_parts.append(f"   {name}: {value}")

        request = get_http_request()
        if request:
            info_parts.append(f"\n🌐 请求信息:")
            info_parts.append(f"   URL: {request.url}")
            info_parts.append(f"   路径: {request.url.path}")
            info_parts.append(f"   方法: {request.method}")
            info_parts.append(f"   查询参数: {dict(request.query_params)}")

            if request.client:
                client_host = getattr(request.client, 'host', 'unknown')
                client_port = getattr(request.client, 'port', 'unknown')
                info_parts.append(f"   客户端: {client_host}:{client_port}")

        if not headers and not request:
            info_parts.append("\nℹ️ 当前不在HTTP请求上下文中")

    except Exception as e:
        info_parts.append(f"\n❌ 获取HTTP信息失败: {e}")

    result = "\n".join(info_parts)
    logger.info(f"🔍 调试信息结果:\n{result}")
    logger.info("=" * 80)

    return result

if __name__ == "__main__":
    logger.info("🚀 启动调试天气服务器...")
    logger.info("=" * 80)
    logger.info("📋 调试服务配置:")
    logger.info("   🌐 传输协议: streamable-http")
    logger.info("   🏠 监听地址: 0.0.0.0")
    logger.info("   🔌 监听端口: 21923")
    logger.info("   🌍 完整地址: http://0.0.0.0:21923")
    logger.info("   📄 日志文件: debug_service.log")
    logger.info("=" * 80)
    
    logger.info("🔧 测试端点:")
    logger.info("   💚 健康检查: http://localhost:21923/health")
    logger.info("   🏠 根路径: http://localhost:21923/")
    logger.info("   🔍 调试信息: http://localhost:21923/debug")
    logger.info("   🔌 MCP 端点: http://localhost:21923/mcp")
    logger.info("=" * 80)
    
    try:
        logger.info("🎯 开始启动调试服务...")
        mcp.run(
            transport="streamable-http",
            host="0.0.0.0",
            port=21923
        )
    except Exception as e:
        logger.error(f"❌ 调试服务启动失败: {e}")
        logger.error(f"💥 错误类型: {type(e).__name__}")
        import traceback
        logger.error(f"📍 错误堆栈:\n{traceback.format_exc()}")
        raise
