#!/bin/bash
# SerpShot Python SDK 发布脚本

set -e

echo "🚀 SerpShot Python SDK 发布脚本"
echo "================================"
echo ""

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

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

# 显示当前版本
echo "📦 当前版本:"
grep -E '^version = ' pyproject.toml || grep -E '__version__ = ' serpshot/__init__.py
echo ""

# 询问是否更新版本
read -p "是否要更新版本号? (y/n): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    read -p "输入新版本号 (例如: 0.1.1): " version
    if [ -n "$version" ]; then
        # 更新 pyproject.toml
        if [[ "$OSTYPE" == "darwin"* ]]; then
            sed -i '' "s/^version = \".*\"/version = \"$version\"/" pyproject.toml
        else
            sed -i "s/^version = \".*\"/version = \"$version\"/" pyproject.toml
        fi
        # 更新 __init__.py
        if [[ "$OSTYPE" == "darwin"* ]]; then
            sed -i '' "s/^__version__ = \".*\"/__version__ = \"$version\"/" serpshot/__init__.py
        else
            sed -i "s/^__version__ = \".*\"/__version__ = \"$version\"/" serpshot/__init__.py
        fi
        echo ""
        echo "✅ 版本已更新为: $version"
        echo ""
    fi
fi

# 构建包
echo "🔨 构建包..."
uv build --no-sources
echo "✅ 构建完成"
echo ""

# 列出构建产物
echo "📦 构建产物:"
ls -lh dist/
echo ""

# 询问是否发布
read -p "是否发布到 PyPI? (y/n): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -z "$UV_PUBLISH_TOKEN" ]; then
        echo "⚠️  未设置 UV_PUBLISH_TOKEN 环境变量"
        read -p "请输入 PyPI token (或按 Ctrl+C 取消): " token
        export UV_PUBLISH_TOKEN="$token"
    fi
    
    echo "📤 发布到 PyPI..."
    uv publish
    echo ""
    echo "✅ 发布成功！"
    echo ""
    echo "🎉 包已发布到 PyPI"
    echo "   等待几分钟后，可以通过以下命令安装:"
    echo "   pip install serpshot"
    echo "   或"
    echo "   uv add serpshot"
else
    echo "⏭️  跳过发布"
    echo "   构建产物在 dist/ 目录，可以稍后手动发布:"
    echo "   uv publish --token your-token"
fi

