#!/usr/bin/env python
"""
发布脚本 - 自动化发布流程
"""
import subprocess
import sys
from pathlib import Path


def run_command(cmd: str, check: bool = True):
    """运行命令"""
    print(f"$ {cmd}")
    result = subprocess.run(cmd, shell=True, check=check)
    return result.returncode == 0


def main():
    """主流程"""
    print("=" * 50)
    print("NSFC Spider 发布脚本")
    print("=" * 50)
    
    # 1. 检查工作目录
    if not Path("pyproject.toml").exists():
        print("❌ 请在项目根目录运行此脚本")
        sys.exit(1)
    
    # 2. 运行测试
    print("\n[1/5] 运行测试...")
    if not run_command("pytest tests/", check=False):
        print("⚠️  测试失败，是否继续？(y/n)")
        if input().lower() != 'y':
            sys.exit(1)
    
    # 3. 清理旧构建
    print("\n[2/5] 清理旧构建...")
    run_command("rm -rf dist/ build/ *.egg-info", check=False)
    
    # 4. 构建包
    print("\n[3/5] 构建包...")
    if not run_command("python -m build"):
        print("❌ 构建失败")
        sys.exit(1)
    
    # 5. 检查包
    print("\n[4/5] 检查包...")
    if not run_command("twine check dist/*"):
        print("❌ 包检查失败")
        sys.exit(1)
    
    # 6. 上传到 PyPI
    print("\n[5/5] 上传到 PyPI...")
    print("选择上传目标:")
    print("  1. TestPyPI (测试)")
    print("  2. PyPI (正式)")
    choice = input("> ").strip()
    
    if choice == "1":
        cmd = "twine upload --repository testpypi dist/*"
    elif choice == "2":
        cmd = "twine upload dist/*"
    else:
        print("❌ 无效选择")
        sys.exit(1)
    
    if not run_command(cmd):
        print("❌ 上传失败")
        sys.exit(1)
    
    print("\n" + "=" * 50)
    print("✅ 发布完成！")
    print("=" * 50)


if __name__ == "__main__":
    main()
