#!/usr/bin/env python3
# 简化版FastAPI服务器 - 端口8080

import sys
import os
from pathlib import Path

# 添加当前目录到Python路径
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

try:
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    import uvicorn
    FASTAPI_AVAILABLE = True
except ImportError:
    print("❌ FastAPI未安装，正在安装基础依赖...")
    import subprocess
    subprocess.run([sys.executable, "-m", "pip", "install", "fastapi", "uvicorn", "requests"])
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    import uvicorn
    FASTAPI_AVAILABLE = True

# 尝试导入app模块
try:
    from app.core.config import settings
    from app.api.v1.endpoints import health, auth, files
    APP_AVAILABLE = True
    print("✅ 完整app模块可用")
except ImportError as e:
    print(f"⚠️  App模块导入失败: {e}")
    print("🔧 使用简化模式启动...")
    APP_AVAILABLE = False

def create_app():
    """创建FastAPI应用"""
    if APP_AVAILABLE:
        # 使用完整的应用
        app = FastAPI(
            title="云盘应用 API",
            description="现代化的云存储Web应用后端API",
            version="1.0.0",
            docs_url="/docs",
            redoc_url="/redoc"
        )

        # CORS中间件
        try:
            app.add_middleware(
                CORSMiddleware,
                allow_origins=settings.ALLOWED_HOSTS,
                allow_credentials=True,
                allow_methods=["*"],
                allow_headers=["*"],
            )
        except:
            # 如果settings有问题，使用默认配置
            app.add_middleware(
                CORSMiddleware,
                allow_origins=["*"],
                allow_credentials=True,
                allow_methods=["*"],
                allow_headers=["*"],
            )

        # 包含路由
        try:
            app.include_router(health.router, prefix="/api/v1", tags=["health"])
            app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
            app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
        except Exception as e:
            print(f"⚠️  路由包含失败: {e}")

        @app.get("/")
        async def root():
            return {
                "message": "云盘应用 API",
                "version": "1.0.1",
                "docs": "/docs",
                "health": "/api/v1/health",
                "mode": "full"
            }

        return app
    else:
        # 创建简化版本的应用
        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",
                "mode": "simplified"
            }

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

        @app.get("/api/v1/health")
        async def api_health():
            import time
            return {
                "status": "healthy",
                "timestamp": time.time(),
                "version": "1.0.0"
            }

        @app.get("/api/v1/test")
        async def test_endpoint():
            return {
                "message": "测试端点正常工作",
                "server": "port 8080",
                "status": "ok"
            }

        return app

def main():
    """主函数"""
    print("🚀 启动云盘应用服务器...")
    print("=" * 50)

    # 创建必要目录
    os.makedirs("logs", exist_ok=True)
    os.makedirs("uploads", exist_ok=True)

    # 创建FastAPI应用
    app = create_app()

    # 获取本机IP
    try:
        import socket
        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"📍 本地访问:")
    print(f"   根路径: http://localhost:8080")
    print(f"   API文档: http://localhost:8080/docs")
    print(f"   ReDoc:   http://localhost:8080/redoc")
    print(f"   健康检查: http://localhost:8080/api/v1/health")
    print(f"   测试端点: http://localhost:8080/api/v1/test")
    print("")
    print(f"🌐 网络访问:")
    print(f"   根路径: http://{local_ip}:8080")
    print(f"   API文档: http://{local_ip}:8080/docs")
    print("")
    print("🔧 服务信息:")
    print(f"   Python版本: {sys.version}")
    print(f"   工作目录: {os.getcwd()}")
    print(f"   启动模式: {'完整版' if APP_AVAILABLE else '简化版'}")
    print("=" * 50)
    print("⏹️  按 Ctrl+C 停止服务")
    print("")

    # 启动服务器
    try:
        uvicorn.run(
            app,
            host="0.0.0.0",
            port=8080,
            reload=False,
            access_log=True,
            log_level="info"
        )
    except KeyboardInterrupt:
        print("\n🛑 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        print("\n💡 可能的解决方案:")
        print("1. 检查端口8080是否被占用")
        print("2. 确保安装了必要的依赖: pip install fastapi uvicorn")
        print("3. 检查防火墙设置")
        return False

    return True

if __name__ == "__main__":
    main()