#!/usr/bin/env python3
"""
启动 MCPStoreWiki 服务的脚本
包含详细的启动信息和错误处理
"""

import subprocess
import sys
import os
import time
import signal
from pathlib import Path

def check_dependencies():
    """检查依赖是否安装"""
    print("🔍 检查依赖...")
    try:
        import fastmcp
        print("   ✅ fastmcp 已安装")
    except ImportError:
        print("   ❌ fastmcp 未安装")
        print("   💡 请运行: pip install fastmcp")
        return False
    
    try:
        import pydantic
        print("   ✅ pydantic 已安装")
    except ImportError:
        print("   ❌ pydantic 未安装")
        print("   💡 请运行: pip install pydantic")
        return False
    
    return True

def check_port(port=21923):
    """检查端口是否被占用"""
    print(f"🔌 检查端口 {port}...")
    import socket
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('localhost', port))
        print(f"   ✅ 端口 {port} 可用")
        return True
    except OSError:
        print(f"   ⚠️ 端口 {port} 已被占用")
        return False

def start_service():
    """启动服务"""
    print("🚀 启动 MCPStoreWiki 服务...")
    
    # 获取脚本目录
    script_dir = Path(__file__).parent
    service_file = script_dir / "mcpstorewiki.py"
    
    if not service_file.exists():
        print(f"❌ 服务文件不存在: {service_file}")
        return False
    
    try:
        # 启动服务进程
        print(f"📁 工作目录: {script_dir}")
        print(f"📄 服务文件: {service_file}")
        print("🎯 启动命令: python mcpstorewiki.py")
        print("-" * 60)
        
        # 使用 subprocess 启动服务
        process = subprocess.Popen(
            [sys.executable, str(service_file)],
            cwd=str(script_dir),
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            bufsize=1
        )
        
        print(f"🆔 进程 ID: {process.pid}")
        print("📋 服务日志:")
        print("=" * 60)
        
        # 实时输出日志
        try:
            for line in process.stdout:
                print(line.rstrip())
                
        except KeyboardInterrupt:
            print("\n⚠️ 收到中断信号，正在关闭服务...")
            process.terminate()
            try:
                process.wait(timeout=5)
                print("✅ 服务已正常关闭")
            except subprocess.TimeoutExpired:
                print("⚠️ 服务未响应，强制关闭...")
                process.kill()
                process.wait()
                print("✅ 服务已强制关闭")
        
        return True
        
    except Exception as e:
        print(f"❌ 启动服务失败: {e}")
        return False

def show_usage_info():
    """显示使用信息"""
    print("\n" + "=" * 60)
    print("📋 服务信息:")
    print("   🌐 本地访问: http://localhost:21923")
    print("   🔗 MCP 端点: http://localhost:21923/mcp")
    print("   💚 健康检查: http://localhost:21923/health")
    print("   📄 日志文件: mcpstorewiki.log")
    print("\n🔧 nginx 反向代理配置示例:")
    print("   location /mcp {")
    print("       proxy_pass http://127.0.0.1:21923;")
    print("       proxy_set_header Host $host;")
    print("       proxy_set_header X-Real-IP $remote_addr;")
    print("       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;")
    print("       proxy_set_header X-Forwarded-Proto $scheme;")
    print("       proxy_http_version 1.1;")
    print("       proxy_set_header Upgrade $http_upgrade;")
    print("       proxy_set_header Connection 'upgrade';")
    print("       proxy_cache_bypass $http_upgrade;")
    print("       proxy_read_timeout 86400;")
    print("   }")
    print("\n💡 测试命令:")
    print("   python test_service.py")
    print("\n⚠️ 停止服务: Ctrl+C")
    print("=" * 60)

def main():
    """主函数"""
    print("🌤️ MCPStoreWiki 服务启动器")
    print("=" * 60)
    
    # 检查依赖
    if not check_dependencies():
        print("\n❌ 依赖检查失败，请安装缺失的依赖")
        return 1
    
    # 检查端口
    if not check_port():
        print("\n⚠️ 端口被占用，服务可能已在运行或被其他程序占用")
        response = input("是否继续启动？(y/N): ")
        if response.lower() != 'y':
            return 1
    
    # 显示使用信息
    show_usage_info()
    
    # 等待用户确认
    input("\n按 Enter 键启动服务...")
    
    # 启动服务
    if start_service():
        print("\n✅ 服务启动完成")
        return 0
    else:
        print("\n❌ 服务启动失败")
        return 1

if __name__ == "__main__":
    sys.exit(main())
