#!/bin/bash
# ========================================
# CI/CD 版本自动同步脚本
# 每次代码更新后自动运行
# ========================================

set -e

REPO_DIR="/root/.openclaw/workspace/jiachenlong"
VERSION_FILE="$REPO_DIR/config/VERSION.json"
CHANGELOG_FILE="$REPO_DIR/config/CHANGELOG.md"

cd "$REPO_DIR"

echo "========================================="
echo "  CI/CD 版本自动同步"
echo "========================================="

# 检查是否有未提交的更改
if [ -n "$(git status --porcelain)" ]; then
    echo "⚠️  有未提交的更改，请先提交"
    exit 1
fi

# 获取当前版本
CURRENT_VERSION=$(python3 -c "import json; print(json.load(open('$VERSION_FILE'))['version'])")
echo "📌 当前版本: $CURRENT_VERSION"

# 解析版本号
MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)

# 询问是否升级版本
echo ""
echo "请选择版本升级类型:"
echo "  1) PATCH (补丁): ${MAJOR}.${MINOR}.$((PATCH+1))"
echo "  2) MINOR (小版本): ${MAJOR}.$((MINOR+1)).0"
echo "  3) MAJOR (大版本): $((MAJOR+1)).0.0"
echo "  4) 自定义版本"
read -p "选择 (1-4): " choice

case $choice in
    1) NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH+1))";;
    2) NEW_VERSION="${MAJOR}.$((MINOR+1)).0";;
    3) NEW_VERSION="$((MAJOR+1)).0.0";;
    4) read -p "输入新版本号: " NEW_VERSION;;
    *) NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH+1))";;
esac

echo "📌 新版本: $NEW_VERSION"

# 更新 VERSION.json
python3 << EOF
import json

with open('$VERSION_FILE') as f:
    v = json.load(f)

old_version = v['version']
v['version'] = '$NEW_VERSION'
v['updated'] = '$(date +%Y-%m-%d)'

# 更新主版本号到所有模块
for section in ['frontend', 'backend']:
    if 'pages' in v['modules'][section]:
        for k in v['modules'][section]['pages']:
            v['modules'][section]['pages'][k] = '$NEW_VERSION'
    if 'routers' in v['modules'][section]:
        for k in v['modules'][section]['routers']:
            v['modules'][section]['routers'][k] = '$NEW_VERSION'
    if 'config' in v['modules'][section]:
        for k in v['modules'][section]['config']:
            v['modules'][section]['config'][k] = '$NEW_VERSION'
    if 'app' in v['modules'][section]:
        for k in v['modules'][section]['app']:
            v['modules'][section]['app'][k] = '$NEW_VERSION'

with open('$VERSION_FILE', 'w') as f:
    json.dump(v, f, indent=2, ensure_ascii=False)

print(f"✅ VERSION.json 已更新: {old_version} → $NEW_VERSION")
EOF

# 同步到所有文件头部
python3 << 'EOF'
import json
import re
import os

VERSION = '$NEW_VERSION'

with open('$VERSION_FILE') as f:
    v = json.load(f)

frontend_pages = v['modules']['frontend']['pages']
backend_routers = v['modules']['backend']['routers']

# 前端文件
for fname in frontend_pages:
    fpath = f"$REPO_DIR/frontend/src/pages/{fname}.jsx"
    if os.path.exists(fpath):
        with open(fpath, 'r') as f:
            content = f.read()
        new_content = re.sub(r'Version: [\d.]+', f'Version: {VERSION}', content, count=1)
        new_content = re.sub(r'\d{4}-\d{2}-\d{2}', '$(date +%Y-%m-%d)', new_content, count=1)
        with open(fpath, 'w') as f:
            f.write(new_content)
        print(f"  ✅ {fname}.jsx")

# 后端文件
for fname in backend_routers:
    fpath = f"$REPO_DIR/backend/app/routers/{fname}.py"
    if os.path.exists(fpath):
        with open(fpath, 'r') as f:
            content = f.read()
        new_content = re.sub(r'Version: [\d.]+', f'Version: {VERSION}', content, count=1)
        new_content = re.sub(r'\d{4}-\d{2}-\d{2}', '$(date +%Y-%m-%d)', new_content, count=1)
        with open(fpath, 'w') as f:
            f.write(new_content)
        print(f"  ✅ {fname}.py")

print(f"✅ 所有文件版本已同步到 {VERSION}")
EOF

# 提交更改
git add .
git commit -m "v$NEW_VERSION - 自动版本更新"
git push

echo ""
echo "========================================="
echo "  ✅ 版本更新完成!"
echo "========================================="
echo "新版本: $NEW_VERSION"
echo "已推送到远程仓库"