#!/bin/bash
# 自动合并通过 CI 检查的 PR
# 用法: ./scripts/auto_merge_prs.sh [target_branch]

GITEA_API="https://git.xiaoxiajianji.com/api/v1"
TOKEN="${GITEA_API_TOKEN:?Please set GITEA_API_TOKEN environment variable}"
REPO="xiaoxia/xiaoxia-saas"
TARGET_BRANCH="${1:-develop}"

echo "=== Checking open PRs targeting $TARGET_BRANCH ==="

# 获取所有 open PR
PRS=$(curl -s -H "Authorization: token $TOKEN" \
  "$GITEA_API/repos/$REPO/pulls?state=open&labels=0" | python3 -c "
import json, sys
data = json.load(sys.stdin)
for pr in data:
    if pr.get('base', {}).get('ref') == '$TARGET_BRANCH':
        if pr.get('mergeable', False):
            print(f\"{pr['number']}|{pr['title']}|{pr.get('mergeable', 'unknown')}\")
")

if [ -z "$PRS" ]; then
    echo "No mergeable PRs found for $TARGET_BRANCH"
    exit 0
fi

echo "$PRS" | while IFS='|' read -r number title mergeable; do
    echo "Merging PR #$number: $title"
    RESULT=$(curl -s -X POST \
      -H "Authorization: token $TOKEN" \
      -H "Content-Type: application/json" \
      "$GITEA_API/repos/$REPO/pulls/$number/merge" \
      -d '{\"merge_method\": \"merge\"}')
    
    if echo "$RESULT" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if 'id' in d else 1)"; then
        echo "  ✅ PR #$number merged successfully"
    else
        echo "  ❌ PR #$number failed: $RESULT"
    fi
done

echo "=== Done ==="
