#!/bin/bash
# PyPI 发布脚本

set -e

echo "🚀 开始发布 mcp-docx-thesis-server 到 PyPI"
echo ""

# 检查是否在项目根目录
if [ ! -f "pyproject.toml" ]; then
    echo "❌ 错误：请在项目根目录运行此脚本"
    exit 1
fi

# 检查是否安装了必要的工具
echo "📦 检查依赖..."
pip install --quiet build twine hatchling 2>/dev/null || true

# 清理旧的构建文件
echo "🧹 清理旧的构建文件..."
rm -rf dist/ build/ *.egg-info/

# 运行测试
echo "🧪 运行测试..."
python -m pytest tests/ -v --tb=short
if [ $? -ne 0 ]; then
    echo "❌ 测试失败，请修复后再发布"
    exit 1
fi

# 运行代码检查
echo "🔍 运行代码检查..."
echo "  - 运行 black..."
python -m black src/ tests/ --check --quiet 2>/dev/null || echo "    ⚠️  代码格式需要调整，运行: black src/ tests/"

echo "  - 运行 ruff..."
python -m ruff check src/ tests/ --quiet 2>/dev/null || echo "    ⚠️  有 lint 警告"

echo "  - 运行 mypy..."
python -m mypy src/ --quiet 2>/dev/null || echo "    ⚠️  有类型检查警告"

# 构建包
echo "📦 构建包..."
python -m build

# 检查构建结果
echo "🔍 检查构建结果..."
wheel_count=$(ls dist/*.whl 2>/dev/null | wc -l)
sdist_count=$(ls dist/*.tar.gz 2>/dev/null | wc -l)

if [ "$wheel_count" -eq 0 ]; then
    echo "❌ 构建失败，未找到 wheel 文件"
    exit 1
fi

if [ "$sdist_count" -eq 0 ]; then
    echo "❌ 构建失败，未找到 sdist 文件"
    exit 1
fi

echo "✅ 构建成功！"
echo ""
ls -lh dist/
echo ""

# 上传到 PyPI
echo "📤 上传到 PyPI..."
echo ""
echo "提示："
echo "  - 首次发布需要先注册 PyPI 账号: https://pypi.org/account/register/"
echo "  - 需要配置 PyPI API Token: https://pypi.org/manage/account/token/"
echo "  - 可以配置 ~/.pypirc 文件或使用环境变量 TWINE_USERNAME/__token__ 和 TWINE_PASSWORD"
echo ""

read -p "确认要上传到 PyPI 吗？首次上传前建议先上传到 TestPyPI 测试 (y/n/test): " confirm

if [ "$confirm" = "test" ]; then
    echo "📤 上传到 TestPyPI..."
    python -m twine upload --repository testpypi dist/*
    echo ""
    echo "✅ 已上传到 TestPyPI"
    echo "   测试安装: pip install --index-url https://test.pypi.org/simple/ mcp-docx-thesis-server"
elif [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    echo "📤 上传到 PyPI..."
    python -m twine upload dist/*
    echo ""
    echo "✅ 发布成功！"
    echo "   安装命令: pip install mcp-docx-thesis-server"
    echo ""
    echo "📝 更新 Cherry Studio 配置:"
    echo '   {'
    echo '     "mcpServers": {'
    echo '       "docx-thesis": {'
    echo '         "command": "python",'
    echo '         "args": ["-m", "mcp_docx_thesis_server.server"]'
    echo '       }'
    echo '     }'
    echo '   }'
else
    echo "❌ 取消上传"
    echo ""
    echo "💡 你可以手动上传:"
    echo "   python -m twine upload dist/*"
fi

echo ""
echo "🎉 完成！"
