#!/usr/bin/env python3
# 带诊断信息的启动脚本

import socket
import sys
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

# 检查端口是否可用
def check_port(port):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('0.0.0.0', port))
        return True
    except OSError:
        return False

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

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

# 更宽松的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",
        "health": "/health"
    }

@app.get("/health")
async def health():
    return {
        "status": "healthy",
        "message": "服务运行正常"
    }

@app.get("/debug")
async def debug_info():
    return {
        "python_version": sys.version,
        "working_directory": ".",
        "available_endpoints": [
            "/",
            "/health",
            "/debug",
            "/docs",
            "/redoc",
            "/openapi.json"
        ]
    }

if __name__ == "__main__":
    port = 8000

    print("🔍 启动前诊断...")
    print(f"Python版本: {sys.version}")
    print(f"工作目录: {(await debug_info())['working_directory']}")

    # 检查端口
    if not check_port(port):
        print(f"❌ 端口 {port} 被占用，尝试使用端口 8001")
        port = 8001

    local_ip = get_local_ip()

    print(f"🚀 启动云盘后端服务...")
    print("=" * 60)
    print(f"📍 本地访问: http://localhost:{port}")
    print(f"📍 网络访问: http://{local_ip}:{port}")
    print(f"📚 API文档: http://localhost:{port}/docs")
    print(f"📚 网络文档: http://{local_ip}:{port}/docs")
    print(f"❤️  健康检查: http://localhost:{port}/health")
    print(f"🔧 调试信息: http://localhost:{port}/debug")
    print(f"⏹️  按 Ctrl+C 停止服务")
    print("=" * 60)

    # 启动时打印所有路由
    @app.on_event("startup")
    async def startup_event():
        print("\n📋 可用路由:")
        for route in app.routes:
            if hasattr(route, 'path') and hasattr(route, 'methods'):
                print(f"  {list(route.methods)} {route.path}")
        print()

    try:
        uvicorn.run(
            app,
            host="0.0.0.0",  # 允许外部访问
            port=port,
            reload=False,
            access_log=True,  # 显示访问日志
            log_level="info"
        )
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        print("\n💡 尝试的解决方案:")
        print("1. 检查防火墙设置")
        print("2. 尝试其他端口: python debug_start.py")
        print("3. 检查是否有其他程序占用端口")