#!/usr/bin/env bash
# 发 acong-tech-xiangqin 到 PyPI（正式 或 canary dev 版本）。
# 自治单体原则：不用 shipyard，但参考了它 src/commands/publish.ts 的做法。
# token 从 vault 取：`vault get pypi api_tokens` 找 name=acong-tech-publish。
#
# 用法:
#   scripts/publish-pypi.sh                 # dry-run（uv build，不发）
#   scripts/publish-pypi.sh --live          # 正式发
#   scripts/publish-pypi.sh --canary        # 发 dev 预发版本 (<base>.devYYYYMMDDHHMM)

set -euo pipefail

MODE="dry-run"
for arg in "$@"; do
    case "$arg" in
        --live) MODE="live" ;;
        --canary) MODE="canary" ;;
        *) echo "未知参数: $arg" >&2; exit 2 ;;
    esac
done

cd "$(dirname "$0")/.."

# --- 1) 取 token ---
TOKEN=$(vault get pypi api_tokens --unmask --json 2>/dev/null | \
    python3 -c "
import json, sys
outer = json.load(sys.stdin)
tokens = json.loads(outer)
match = next((t for t in tokens if t.get('name') == 'acong-tech-publish'), None)
if not match or not match.get('token'):
    print('vault.pypi.api_tokens missing acong-tech-publish', file=sys.stderr)
    sys.exit(1)
print(match['token'])
")

if [[ -z "$TOKEN" ]]; then
    echo "✗ vault 取 PyPI token 失败" >&2
    exit 1
fi

# --- 2) 处理 canary 版本 ---
BASE_VERSION=$(grep -E '^version = ' pyproject.toml | head -1 | sed -E 's/version = "([^"]+)"/\1/')
EFFECTIVE_VERSION="$BASE_VERSION"

if [[ "$MODE" == "canary" ]]; then
    TS=$(date +%Y%m%d%H%M)
    # PEP 440 dev 后缀（canary 不是合法 PEP 440 identifier）
    CLEAN=$(echo "$BASE_VERSION" | sed -E 's/\.dev[0-9]+$//')
    EFFECTIVE_VERSION="${CLEAN}.dev${TS}"
    sed -i.bak -E "s/^version = \"[^\"]+\"/version = \"${EFFECTIVE_VERSION}\"/" pyproject.toml
    echo "▸ canary: $BASE_VERSION → $EFFECTIVE_VERSION"
fi

# 恢复原 version（trap）
cleanup() {
    if [[ "$MODE" == "canary" ]] && [[ -f pyproject.toml.bak ]]; then
        mv pyproject.toml.bak pyproject.toml
    fi
}
trap cleanup EXIT

# --- 3) build ---
echo "▸ uv build"
rm -rf dist/
uv build 2>&1 | tail -5

# --- 4) publish ---
if [[ "$MODE" == "dry-run" ]]; then
    echo "✓ dry-run 成功：dist/ 已产生 wheel + sdist（未发布）"
    ls -la dist/
    exit 0
fi

echo "▸ uv publish → PyPI (acong-tech-xiangqin@${EFFECTIVE_VERSION})"
UV_PUBLISH_TOKEN="$TOKEN" uv publish 2>&1 | tail -10

echo "✓ 已发 https://pypi.org/project/acong-tech-xiangqin/${EFFECTIVE_VERSION}/"
