#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速启动和恢复脚本
"""

import os
import sys
import subprocess
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        return False
    print(f"✓ Python版本: {sys.version}")
    return True

def check_virtual_env():
    """检查虚拟环境"""
    venv_path = Path('venv')
    if venv_path.exists():
        print("✓ 虚拟环境存在")
        return True
    else:
        print("✗ 虚拟环境不存在，正在创建...")
        try:
            subprocess.run([sys.executable, '-m', 'venv', 'venv'], check=True)
            print("✓ 虚拟环境创建成功")
            return True
        except subprocess.CalledProcessError:
            print("✗ 虚拟环境创建失败")
            return False

def activate_virtual_env():
    """激活虚拟环境"""
    if sys.platform == "win32":
        activate_script = Path('venv/Scripts/activate')
    else:
        activate_script = Path('venv/bin/activate')

    if activate_script.exists():
        print("✓ 虚拟环境激活脚本存在")
        return True
    else:
        print("✗ 虚拟环境激活脚本不存在")
        return False

def install_dependencies():
    """安装依赖"""
    print("安装依赖包...")

    if sys.platform == "win32":
        pip_path = 'venv/Scripts/pip'
        python_path = 'venv/Scripts/python'
    else:
        pip_path = 'venv/bin/pip'
        python_path = 'venv/bin/python'

    # 升级pip
    try:
        subprocess.run([python_path, '-m', 'pip', 'install', '--upgrade', 'pip'], check=True)
        print("✓ pip升级成功")
    except subprocess.CalledProcessError:
        print("✗ pip升级失败")

    # 安装基础依赖
    basic_packages = [
        'fastapi==0.104.1',
        'uvicorn[standard]==0.24.0',
        'sqlalchemy==2.0.23',
        'pymysql==1.1.0',
        'python-jose[cryptography]==3.3.0',
        'passlib[bcrypt]==1.7.4',
        'python-multipart==0.0.6',
        'pydantic==2.5.0',
        'pydantic-settings==2.1.0',
        'httpx==0.25.2',
        'python-dotenv==1.0.0',
        'loguru>=0.7.0'
    ]

    try:
        for package in basic_packages:
            print(f"安装 {package}...")
            subprocess.run([pip_path, 'install', package], check=True)
        print("✓ 依赖安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖安装失败: {e}")
        return False

def create_basic_app_structure():
    """创建基本的app结构"""
    print("创建基本app结构...")

    # 创建目录
    directories = [
        'app',
        'app/core',
        'app/api/v1/endpoints'
    ]

    for dir_path in directories:
        Path(dir_path).mkdir(parents=True, exist_ok=True)
        print(f"✓ 创建目录: {dir_path}")

    # 创建__init__.py文件
    init_files = [
        ('app/__init__.py', '"""云盘应用包"""\n'),
        ('app/core/__init__.py', '"""核心模块包"""\n'),
        ('app/api/__init__.py', '"""API模块包"""\n'),
        ('app/api/v1/__init__.py', '"""API v1模块包"""\n'),
        ('app/api/v1/endpoints/__init__.py', '"""API端点模块包"""\n')
    ]

    for file_path, content in init_files:
        full_path = Path(file_path)
        if not full_path.exists():
            full_path.write_text(content, encoding='utf-8')
            print(f"✓ 创建文件: {file_path}")

def create_essential_files():
    """创建必要的文件"""
    print("创建必要的文件...")

    # app/core/config.py
    config_content = '''from pydantic_settings import BaseSettings
from typing import List

class Settings(BaseSettings):
    ENVIRONMENT: str = "development"
    DEBUG: bool = True
    DATABASE_URL: str = "mysql+pymysql://mytest_db:mytest_db@101.126.85.76:3306/mytest_db"
    REDIS_URL: str = "redis://localhost:6379"
    JWT_SECRET_KEY: str = "your-super-secret-jwt-key-change-in-production"
    JWT_ALGORITHM: str = "HS256"
    JWT_EXPIRE_MINUTES: int = 30
    ALLOWED_HOSTS: List[str] = ["*"]
    MAX_FILE_SIZE: int = 10 * 1024 * 1024
    UPLOAD_DIR: str = "uploads"

    class Config:
        env_file = ".env"
        case_sensitive = True

settings = Settings()
'''

    Path('app/core/config.py').write_text(config_content, encoding='utf-8')
    print("✓ 创建 app/core/config.py")

    # app/api/v1/endpoints/health.py
    health_content = '''from fastapi import APIRouter
from datetime import datetime

router = APIRouter()

@router.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow(),
        "version": "1.0.0"
    }

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

    Path('app/api/v1/endpoints/health.py').write_text(health_content, encoding='utf-8')
    print("✓ 创建 app/api/v1/endpoints/health.py")

def create_simple_main():
    """创建简化的main.py"""
    print("创建简化的main.py...")

    main_content = '''import os
import sys
from pathlib import Path

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

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.endpoints import health

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

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(health.router, prefix="/api/v1", tags=["health"])

if __name__ == "__main__":
    import uvicorn
    print("启动云盘后端服务...")
    print("访问地址: http://localhost:8000")
    print("API文档: http://localhost:8000/docs")

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        reload=False
    )
'''

    Path('main.py').write_text(main_content, encoding='utf-8')
    print("✓ 创建 main.py")

def start_project():
    """启动项目"""
    print("启动项目...")

    if sys.platform == "win32":
        python_path = 'venv/Scripts/python'
    else:
        python_path = 'venv/bin/python'

    try:
        # 直接运行main.py
        subprocess.run([python_path, 'main.py'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"启动失败: {e}")
        return False
    except KeyboardInterrupt:
        print("服务已停止")
        return True

def main():
    """主函数"""
    print("=== 云盘后端快速启动脚本 ===")

    # 检查Python版本
    if not check_python_version():
        return

    # 检查和创建虚拟环境
    if not check_virtual_env():
        print("虚拟环境创建失败")
        return

    # 安装依赖
    if not install_dependencies():
        print("依赖安装失败")
        return

    # 创建基本结构
    create_basic_app_structure()

    # 创建必要文件
    create_essential_files()

    # 创建简化main.py
    create_simple_main()

    # 创建日志和上传目录
    Path('logs').mkdir(exist_ok=True)
    Path('uploads').mkdir(exist_ok=True)

    print("\n=== 准备完成 ===")
    print("现在启动项目...")

    # 启动项目
    start_project()

if __name__ == '__main__':
    main()