# -*- mode: python ; coding: utf-8 -*-

import sys
from pathlib import Path

# 项目根目录
ROOT_DIR = Path.cwd()

# 需要包含的数据文件
datas = [
    (str(ROOT_DIR / 'app'), 'app'),  # 包含整个app目录
    ('.env.example', '.'),           # 包含环境配置示例文件
]

# 可选数据文件（如果存在才包含）
optional_files = [
    ('database', 'database'),        # 包含数据库相关文件
]

# 添加可选数据文件
for src, dst in optional_files:
    src_path = ROOT_DIR / src
    if src_path.exists():
        datas.append((src, dst))
        print(f"包含可选数据文件: {src}")
    else:
        print(f"跳过可选数据文件: {src} (不存在)")

# 隐式导入的模块
hiddenimports = [
    # FastAPI相关
    'fastapi',
    'fastapi.templating',
    'fastapi.staticfiles',
    'fastapi.middleware',
    'fastapi.middleware.cors',
    'fastapi.responses',
    'fastapi.exceptions',
    # Uvicorn相关
    'uvicorn',
    'uvicorn.lifespan.on',
    'uvicorn.lifespan.off',
    'uvicorn.lifespan.on_startup',
    'uvicorn.lifespan.on_shutdown',
    'uvicorn.protocols.http.auto',
    'uvicorn.protocols.http.h11_impl',
    'uvicorn.protocols.websockets.auto',
    'uvicorn.protocols.websockets.wsproto_impl',
    'uvicorn.logging',
    'uvicorn.main',
    # Starlette相关
    'starlette',
    'starlette.applications',
    'starlette.middleware',
    'starlette.middleware.cors',
    'starlette.routing',
    'starlette.responses',
    'starlette.staticfiles',
    'starlette.exceptions',
    # Pydantic相关
    'pydantic',
    'pydantic.main',
    'pydantic.fields',
    'pydantic_settings',
    'pydantic.networks',
    'pydantic.types',
    'pydantic.validators',
    'pydantic.json_schema',
    # SQLAlchemy相关
    'sqlalchemy',
    'sqlalchemy.dialects',
    'sqlalchemy.dialects.mysql',
    'sqlalchemy.engine',
    'sqlalchemy.ext.declarative',
    'sqlalchemy.orm',
    'sqlalchemy.sql',
    'sqlalchemy.pool',
    'sqlalchemy.event',
    # 认证相关
    'passlib',
    'passlib.hash',
    'passlib.hash.bcrypt',
    'passlib.context',
    'python_jose',
    'python_jose.jwk',
    'python_jose.jws',
    'python_jose.jwt',
    'python_jose.backends',
    'python_jose.backends.cryptography',
    'python_multipart',
    'multipart',
    'multipart.multipart',
    # 数据库驱动
    'pymysql',
    'pymysql.connections',
    'pymysql.cursors',
    'pymysql.charset',
    # Redis相关
    'redis',
    'redis.client',
    'redis.connection',
    'redis.exceptions',
    'redis.commands',
    'redis.asyncio',
    # HTTP客户端
    'httpx',
    'httpx.client',
    'httpx._client',
    'httpx._transports',
    'httpx._transports.default',
    # 工具库
    'loguru',
    'python_dotenv',
    'dotenv',
    'dotenv.main',
    # Alembic（数据库迁移）
    'alembic',
    'alembic.command',
    'alembic.config',
    'alembic.script',
    'alembic.runtime',
    'alembic.migration',
    # 其他依赖
    'email.utils',
    'email.mime',
    'yaml',
    'toml',
    'json',
    'base64',
    'hashlib',
    'datetime',
    'uuid',
    'os',
    'sys',
    'pathlib',
    'typing',
    'collections',
    'itertools',
    'functools',
    'time',
    'math',
    're',
    'socket',
    'threading',
    'asyncio',
    'concurrent.futures',
    # MySQL相关
    'cryptography',
    'cryptography.hazmat',
    'cryptography.hazmat.backends',
    'cryptography.hazmat.backends.openssl',
    'cryptography.hazmat.primitives',
    'cryptography.hazmat.primitives.hashes',
    'cryptography.hazmat.primitives.kdf',
    'cryptography.hazmat.primitives.ciphers',
    # Jinja2模板引擎（FastAPI可能用到）
    'jinja2',
    'jinja2.utils',
    'jinja2.environment',
    # 文件处理相关
    'mimetypes',
    'tempfile',
    'shutil',
    'gzip',
    'zipfile',
    # 命令行参数处理
    'argparse',
    'getopt',
    # 编码相关
    'codecs',
    'encodings',
    'encodings.utf_8',
    'encodings.ascii',
    'encodings.latin1',
    'encodings.cp1252',
    # 正则表达式
    'regex',
    # 随机数
    'random',
    'secrets',
    # 日期时间处理
    'calendar',
    'time',
    # 网络相关
    'urllib',
    'urllib.parse',
    'urllib.request',
    'http',
    'http.server',
    'socketserver',
    # 异步相关
    'asyncio.runners',
    'asyncio.events',
    'asyncio.locks',
    # 多进程
    'multiprocessing',
    'multiprocessing.pool',
    # 系统信号
    'signal',
    # 环境变量
    'environ',
]

block_cipher = None

a = Analysis(
    ['main.py'],
    pathex=[str(ROOT_DIR)],
    binaries=[],
    datas=datas,
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[
        # 排除不需要的大型库以减小体积
        'Pillow', 'PIL', 'numpy', 'scipy', 'matplotlib', 'pandas',
        'torch', 'tensorflow', 'keras', 'sklearn', 'opencv',
        'jupyter', 'notebook', 'ipython', 'sphinx', 'pytest',
        'setuptools', 'pip', 'wheel', 'twine',
        'PyQt5', 'PyQt6', 'PySide2', 'PySide6', 'tkinter',
        'gtk', 'wx', 'fltk', 'kivy',
        # 排除开发工具
        'black', 'flake8', 'mypy', 'pylint', 'isort',
        'pytest', 'unittest', 'doctest',
        # 排除数据库工具
        'psycopg2', 'cx_Oracle', 'sqlite3',
    ],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='cloud-drive-server',
    debug=False,
    bootloader_ignore_signals=False,
    strip=True,  # Linux下启用strip以减小体积
    upx=True,   # 启用UPX压缩
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,  # 控制台应用，便于查看日志
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch='linux64',  # 指定目标架构为64位Linux
    codesign_identity=None,
    entitlements_file=None,
)