#!/usr/bin/env python3
"""部署前检查脚本"""

import sys
from pathlib import Path
import importlib.util

def check_file(path, desc):
    if Path(path).exists():
        print(f"✅ {desc}: {path}")
        return True
    else:
        print(f"❌ 缺失: {desc} → {path}")
        return False

def check_module(module, desc):
    if importlib.util.find_spec(module):
        print(f"✅ Python模块: {module}")
        return True
    else:
        print(f"❌ 缺失Python模块: {module}（需运行 pip install -r requirements.txt）")
        return False

def main():
    print("========================================")
    print("宇之然内容创作平台 - 部署前检查")
    print("========================================\n")

    all_ok = True

    # 1. 项目结构检查
    print("【1】项目结构")
    base = Path(__file__).parent
    paths = [
        (base / "backend" / "app" / "main.py", "后端入口"),
        (base / "frontend" / "index.html", "前端主文件"),
        (base / "data", "数据目录"),
        (base / "logs", "日志目录"),
        (base / ".." / "automation" / "data" / "sustainability_topics.json", "选题JSON"),
        (base / ".." / "scripts" / "creator.py", "创作脚本"),
        (base / ".." / "scripts" / "publisher.py", "发布脚本"),
    ]
    for p, desc in paths:
        all_ok &= check_file(p, desc)
    print()

    # 2. Python依赖检查
    print("【2】Python依赖")
    modules = ["fastapi", "uvicorn", "sqlalchemy", "pydantic"]
    for m in modules:
        all_ok &= check_module(m, "模块")
    print()

    # 3. 配置检查
    print("【3】配置与环境")
    backend_dir = base / "backend"
    venv_ok = (backend_dir / "venv").exists()
    if venv_ok:
        print("✅ 虚拟环境存在")
    else:
        print("⚠️  虚拟环境不存在（可选，建议创建）")
    print()

    # 4. 端口检查（从环境变量或脚本参数获取端口）
    import os
    import sys
    port = int(os.environ.get('YZR_PORT', sys.argv[1] if len(sys.argv) > 1 else '8001'))
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.bind(("0.0.0.0", port))
        print(f"✅ 端口 {port} 可用")
    except OSError as e:
        print(f"❌ 端口 {port} 被占用: {e}")
        all_ok = False
    finally:
        s.close()
    print()

    print("========================================")
    if all_ok:
        print("✅ 检查通过，可以运行 ./run.sh 启动服务")
    else:
        print("❌ 存在问题，请根据上述提示修复")
    print("========================================")

    return 0 if all_ok else 1

if __name__ == "__main__":
    sys.exit(main())
