#!/bin/bash
# 发布 arc-deploy 到 PyPI
#
# 用法：
#   ./publish.sh        # 发布到 Test PyPI（测试）
#   ./publish.sh prod   # 发布到正式 PyPI

set -e

ENVIRONMENT=${1:-test}

echo "================================================"
echo "🚀 发布 arc-deploy 到 PyPI"
echo "================================================"
echo ""

# 检查 uv 是否安装
if ! command -v uv &> /dev/null; then
    echo "❌ 未找到 uv，请先安装："
    echo "   curl -LsSf https://astral.sh/uv/install.sh | sh"
    exit 1
fi

echo "✓ 找到 uv: $(uv --version)"

# 检查工作目录
if [ ! -f "pyproject.toml" ]; then
    echo "❌ 请在 cli 目录下运行此脚本"
    exit 1
fi

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

# 构建 package
echo ""
echo "📦 构建 package..."
uv build

# 检查构建产物
echo ""
echo "✓ 构建完成："
ls -lh dist/

# 发布
echo ""
if [ "$ENVIRONMENT" = "prod" ]; then
    echo "🚀 发布到正式 PyPI..."
    echo ""
    read -p "⚠️  确认发布到正式 PyPI? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "已取消"
        exit 1
    fi

    uv publish

    echo ""
    echo "================================================"
    echo "✅ 发布成功！"
    echo "================================================"
    echo ""
    echo "安装命令："
    echo "  pip install arc-deploy"
    echo "  # 或"
    echo "  uv pip install arc-deploy"
    echo ""
    echo "PyPI 页面："
    echo "  https://pypi.org/project/arc-deploy/"

else
    echo "🧪 发布到 Test PyPI（测试环境）..."
    echo ""

    uv publish --publish-url https://test.pypi.org/legacy/

    echo ""
    echo "================================================"
    echo "✅ 发布到 Test PyPI 成功！"
    echo "================================================"
    echo ""
    echo "测试安装命令："
    echo "  pip install --index-url https://test.pypi.org/simple/ arc-deploy"
    echo "  # 或"
    echo "  uv pip install --index-url https://test.pypi.org/simple/ arc-deploy"
    echo ""
    echo "Test PyPI 页面："
    echo "  https://test.pypi.org/project/arc-deploy/"
    echo ""
    echo "如果测试通过，运行以下命令发布到正式 PyPI："
    echo "  ./publish.sh prod"
fi

echo ""
