#!/usr/bin/env python3
# 不依赖loguru的启动脚本

import os
import sys
import logging
from pathlib import Path

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

# 配置标准日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

logger.info("Starting Cloud Drive Application Server...")

# 导入FastAPI相关
try:
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    import uvicorn
    logger.info("FastAPI dependencies available")
except ImportError as e:
    logger.error(f"FastAPI import failed: {e}")
    logger.error("Please install dependencies: pip install fastapi uvicorn")
    sys.exit(1)

# 尝试导入app模块
try:
    from app.core.config import settings
    from app.api.v1.endpoints import health, auth, files
    APP_AVAILABLE = True
    logger.info("Full app module available")
except ImportError as e:
    logger.warning(f"App module import failed: {e}")
    logger.info("Using simplified mode")
    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 Exception as e:
            logger.warning(f"CORS configuration failed: {e}")
            # 使用默认配置
            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:
            logger.warning(f"Router inclusion failed: {e}")

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

        # 添加缺失的端点
        @app.get("/health")
        async def health_endpoint():
            import time
            return {
                "success": True,
                "data": {
                    "status": "healthy",
                    "service": "cloud-drive-api",
                    "environment": "development",
                    "timestamp": int(time.time())
                },
                "message": "API服务运行正常"
            }

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

        @app.get("/info")
        async def info_endpoint():
            return {
                "mode": "full",
                "python_version": str(sys.version),
                "status": "running",
                "app_type": "FastAPI"
            }

        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("/test")
        async def test_endpoint():
            return {
                "message": "测试端点正常工作",
                "server": "port 8080",
                "status": "ok"
            }

        @app.get("/health")
        async def health_endpoint():
            import time
            return {
                "success": True,
                "data": {
                    "status": "healthy",
                    "service": "cloud-drive-api",
                    "environment": "development",
                    "timestamp": int(time.time())
                },
                "message": "API服务运行正常"
            }

        @app.get("/info")
        async def info_endpoint():
            return {
                "mode": "simplified",
                "python_version": str(sys.version),
                "status": "running",
                "app_type": "FastAPI"
            }

        return app

def main():
    """主函数"""
    logger.info("Initializing Cloud Drive Application...")

    # 创建必要目录
    os.makedirs("logs", exist_ok=True)
    os.makedirs("uploads", exist_ok=True)
    logger.info("Created necessary directories")

    # 创建FastAPI应用
    app = create_app()
    logger.info("FastAPI application created")

    # 获取本机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"
        logger.warning("Could not determine local IP, using 127.0.0.1")

    # 显示启动信息
    logger.info("=" * 50)
    logger.info(f"Local access:")
    logger.info(f"   Root path: http://localhost:8080")
    logger.info(f"   API docs: http://localhost:8080/docs")
    logger.info(f"   ReDoc:   http://localhost:8080/redoc")
    logger.info(f"   Health check: http://localhost:8080/api/v1/health")
    logger.info("")
    logger.info(f"Network access:")
    logger.info(f"   Root path: http://{local_ip}:8080")
    logger.info(f"   API docs: http://{local_ip}:8080/docs")
    logger.info("")
    logger.info("Service information:")
    logger.info(f"   Python version: {sys.version}")
    logger.info(f"   Working directory: {os.getcwd()}")
    logger.info(f"   Mode: {'Full' if APP_AVAILABLE else 'Simplified'}")
    logger.info("=" * 50)
    logger.info("Press Ctrl+C to stop service")

    # 启动服务器
    try:
        uvicorn.run(
            app,
            host="0.0.0.0",
            port=8080,
            reload=False,
            access_log=True,
            log_level="info"
        )
    except KeyboardInterrupt:
        logger.info("Server stopped by user")
    except Exception as e:
        logger.error(f"Startup failed: {e}")
        logger.info("Possible solutions:")
        logger.info("1. Check if port 8080 is occupied")
        logger.info("2. Ensure dependencies are installed: pip install fastapi uvicorn")
        logger.info("3. Check firewall settings")
        return False

    return True

if __name__ == "__main__":
    main()