#!/usr/bin/env python3
# 简化版启动脚本，解决模块导入问题

import os
import sys
from pathlib import Path

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

print(f"当前目录: {current_dir}")
print(f"Python路径: {sys.path[:3]}...")

# 检查必要目录
required_dirs = ['app', 'app/core', 'app/api/v1/endpoints']
for dir_path in required_dirs:
    full_path = current_dir / dir_path
    if not full_path.exists():
        print(f"创建目录: {dir_path}")
        full_path.mkdir(parents=True, exist_ok=True)

        # 创建__init__.py
        init_file = full_path / '__init__.py'
        if not init_file.exists():
            init_file.write_text(f'"""{dir_path} 模块包"""\n')

try:
    # 测试导入
    print("测试导入模块...")
    from app.core.config import settings
    print("✓ app.core.config 导入成功")

    from app.api.v1.endpoints import health, auth, files
    print("✓ app.api.v1.endpoints 导入成功")

    # 启动FastAPI应用
    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    import uvicorn

    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.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"])

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

    print("✓ FastAPI应用创建成功")

    # 启动服务
    print("启动服务...")
    print("访问地址: http://localhost:8000")
    print("API文档: http://localhost:8000/docs")

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        reload=False  # 关闭热重载避免问题
    )

except ImportError as e:
    print(f"导入错误: {e}")
    print("\n可能的解决方案:")
    print("1. 确保在正确的目录运行（包含main.py的目录）")
    print("2. 安装依赖: pip install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru")
    print("3. 检查app目录结构是否完整")
    sys.exit(1)

except Exception as e:
    print(f"启动错误: {e}")
    sys.exit(1)