#!/bin/bash
# ========================================
# 版本同步脚本 - 只更新修改的文件
# 用法: ./scripts/version_sync.sh [patch|minor|major|custom]
# ========================================

set -e

REPO_DIR="/root/.openclaw/workspace/jiachenlong"
VERSION_FILE="$REPO_DIR/config/VERSION.json"
cd "$REPO_DIR"

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

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

# 根据参数决定新版本
case "${1:-patch}" in
    patch) NEW="$MAJOR.$MINOR.$((PATCH+1))";;
    minor) NEW="$MAJOR.$((MINOR+1)).0";;
    major) NEW="$((MAJOR+1)).0.0";;
    *) NEW="${1:-$CURRENT}";;
esac

echo "📌 新版本: $NEW"

# 1. 更新VERSION.json主版本号
python3 << EOF
import json

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

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

with open('$VERSION_FILE', 'w') as f:
    json.dump(v, f, indent=2, ensure_ascii=False)
print("✅ VERSION.json 主版本已更新")
EOF

# 2. 同步VERSION.json中的版本到文件头部（只同步VERSION.json中已记录的版本）
python3 << 'EOF'
import json
import re
import os

VERSION = '$NEW'
REPO = '$REPO_DIR'

with open(f'{REPO}/config/VERSION.json') as f:
    v = json.load(f)

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

# 前端
for fname, ver in pages.items():
    fpath = f'{REPO}/frontend/src/pages/{fname}.jsx'
    if os.path.exists(fpath):
        with open(fpath, 'r') as f:
            content = f.read()
        # 只更新VERSION.json中记录的版本
        new_content = re.sub(r'Version: [\d.]+', f'Version: {ver}', content, count=1)
        with open(fpath, 'w') as f:
            f.write(new_content)
        print(f"  ✅ {fname}.jsx: {ver}")

# 后端
for fname, ver in routers.items():
    fpath = f'{REPO}/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: {ver}', content, count=1)
        with open(fpath, 'w') as f:
            f.write(new_content)
        print(f"  ✅ {fname}.py: {ver}")

print("✅ 所有文件版本已同步")
EOF

# 3. 提交
git add .
git commit -m "v$NEW - 版本自动更新" || echo "无新更改"

echo ""
echo "✅ 完成！版本: $CURRENT → $NEW"