#!/usr/bin/env python3
# 专门解决docs无法访问问题的脚本

import subprocess
import socket
import sys
from pathlib import Path

def check_fastapi_docs():
    """检查FastAPI docs相关的常见问题"""
    print("🔍 FastAPI Docs 诊断工具")
    print("=" * 50)

    # 1. 检查FastAPI版本
    try:
        import fastapi
        print(f"✓ FastAPI版本: {fastapi.__version__}")
    except ImportError:
        print("❌ FastAPI未安装")
        return False

    # 2. 检查uvicorn版本
    try:
        import uvicorn
        print(f"✓ Uvicorn版本: {uvicorn.__version__}")
    except ImportError:
        print("❌ Uvicorn未安装")
        return False

    # 3. 检查端口占用
    print("\n📡 网络诊断:")
    for port in [8000, 8001, 8002]:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex(('127.0.0.1', port))
        if result == 0:
            print(f"❌ 端口 {port} 被占用")
        else:
            print(f"✓ 端口 {port} 可用")
        sock.close()

    # 4. 获取本机IP
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        print(f"✓ 本机IP: {local_ip}")
    except:
        local_ip = "127.0.0.1"
        print(f"⚠️  使用回环地址: {local_ip}")

    # 5. 测试不同的host配置
    print("\n🧪 测试不同配置:")

    test_configs = [
        ("127.0.0.1", "仅本地访问"),
        ("0.0.0.0", "允许外部访问"),
        ("localhost", "主机名访问")
    ]

    for host, desc in test_configs:
        print(f"  {host} - {desc}")

    return True, local_ip

def create_working_server():
    """创建可以正常访问docs的服务器"""
    print("\n🔧 创建可用的服务器配置...")

    server_content = '''#!/usr/bin/env python3
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import socket

app = FastAPI(
    title="云盘应用 API",
    description="现代化的云存储Web应用后端API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    openapi_url="/openapi.json"
)

# 确保CORS配置正确
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {
        "message": "云盘应用 API",
        "version": "1.0.0",
        "docs": "/docs",
        "redoc": "/redoc",
        "openapi": "/openapi.json"
    }

@app.get("/health")
async def health():
    return {
        "status": "healthy",
        "docs_available": True
    }

@app.get("/test-docs")
async def test_docs():
    """测试docs是否可用"""
    return {
        "docs_url": "/docs",
        "redoc_url": "/redoc",
        "openapi_url": "/openapi.json",
        "message": "如果看到这个页面，说明服务正常运行，请尝试访问 /docs"
    }

def get_available_port():
    """获取可用端口"""
    for port in range(8000, 8010):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('0.0.0.0', port))
                return port
        except OSError:
            continue
    return None

if __name__ == "__main__":
    port = get_available_port()
    if port is None:
        print("❌ 无法找到可用端口")
        sys.exit(1)

    # 获取本机IP
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
    except:
        local_ip = "127.0.0.1"

    print(f"🚀 启动服务在端口 {port}")
    print("=" * 60)
    print(f"📍 本地访问:")
    print(f"   根路径: http://localhost:{port}")
    print(f"   API文档: http://localhost:{port}/docs")
    print(f"   ReDoc:   http://localhost:{port}/redoc")
    print(f"   测试页面: http://localhost:{port}/test-docs")
    print("")
    print(f"📍 网络访问:")
    print(f"   根路径: http://{local_ip}:{port}")
    print(f"   API文档: http://{local_ip}:{port}/docs")
    print(f"   ReDoc:   http://{local_ip}:{port}/redoc")
    print("=" * 60)
    print("💡 如果无法访问，请检查:")
    print("   1. 防火墙设置")
    print("   2. 网络连接")
    print("   3. 浏览器是否阻止访问")
    print("   4. 尝试不同的浏览器")
    print("⏹️  按 Ctrl+C 停止服务")
    print("=" * 60)

    try:
        uvicorn.run(
            app,
            host="0.0.0.0",
            port=port,
            reload=False,
            access_log=True,
            log_level="info"
        )
    except KeyboardInterrupt:
        print("\\n服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
'''

    with open('working_server.py', 'w', encoding='utf-8') as f:
        f.write(server_content)

    print("✓ 已创建 working_server.py")
    return True

def test_curl_commands():
    """提供curl测试命令"""
    print("\n🌐 提供测试命令:")

    print("\\n1. 测试根路径:")
    print("curl http://localhost:8000")

    print("\\n2. 测试健康检查:")
    print("curl http://localhost:8000/health")

    print("\\n3. 测试API文档端点:")
    print("curl http://localhost:8000/docs")

    print("\\n4. 测试OpenAPI JSON:")
    print("curl http://localhost:8000/openapi.json")

    print("\\n5. 测试ReDoc:")
    print("curl http://localhost:8000/redoc")

def main():
    """主函数"""
    # 检查环境
    success, local_ip = check_fastapi_docs()

    if not success:
        print("\\n❌ 环境检查失败，请安装必要的依赖")
        print("pip install fastapi uvicorn")
        return

    # 创建可用服务器
    create_working_server()

    # 提供测试命令
    test_curl_commands()

    print("\\n" + "=" * 60)
    print("🎯 解决方案:")
    print("1. 运行: python working_server.py")
    print("2. 在浏览器中访问显示的URL")
    print("3. 如果仍然无法访问，请检查:")
    print("   - 防火墙设置")
    print("   - 浏览器阻止")
    print("   - 网络代理设置")
    print("=" * 60)

if __name__ == '__main__':
    main()