#!/bin/bash
# verify-api-compatibility.sh - 验证 API 契约兼容性
# 依赖: git, jq (可选)
# 用法: ./verify-api-compatibility.sh [base-branch]

set -e

BASE_BRANCH=${1:-main}
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== API 契约兼容性检查 ==="
echo "对比分支: ${BASE_BRANCH}"
echo ""

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

pass() { echo -e "${GREEN}[PASS]${NC} $1"; }
fail() { echo -e "${RED}[FAIL]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

# 获取变更的 handler 文件
CHANGED_HANDLERS=$(git diff ${BASE_BRANCH} --name-only | grep -E "handler.*\.go$" || true)

if [ -z "$CHANGED_HANDLERS" ]; then
    pass "无 handler 文件变更"
    exit 0
fi

echo "变更的 Handler 文件:"
echo "$CHANGED_HANDLERS"
echo ""

# 检查是否有字段删除
for file in $CHANGED_HANDLERS; do
    if [ -f "$file" ]; then
        # 检查是否有结构体字段删除
        DELETED_LINES=$(git diff ${BASE_BRANCH} -- "$file" | grep "^-" | grep -E "^\s+\w+\s+\w+" || true)
        if [ -n "$DELETED_LINES" ]; then
            warn "可能的字段删除 in $file:"
            echo "$DELETED_LINES"
        fi

        # 检查是否有新增必填字段
        ADDED_REQUIRED=$(git diff ${BASE_BRANCH} -- "$file" | grep "^+" | grep 'binding:"required"' || true)
        if [ -n "$ADDED_REQUIRED" ]; then
            warn "新增必填字段 in $file (可能是 Breaking Change):"
            echo "$ADDED_REQUIRED"
        fi
    fi
done

echo ""
echo "=== 检查完成 ==="
echo "请人工确认上述变更是否为 Breaking Change"
