#!/bin/bash

# Git同步问题修复脚本
# 解决小说项目同步中断问题

set -e

echo "🔧 开始修复Git同步问题..."
echo "==============================="

WORKSPACE_DIR="/root/.openclaw/workspace"
cd "$WORKSPACE_DIR"

# 1. 检查当前状态
echo "📊 当前Git状态:"
git status --short

echo ""
echo "1️⃣ 修复子模块问题..."

# 检查子模块状态
echo "   📁 子模块状态:"
git submodule status

# 更新子模块
echo "   🔄 更新子模块..."
git submodule update --init --recursive

echo ""
echo "2️⃣ 清理重复版本..."

# 统计重复文件
echo "   📈 重复文件统计:"
find tomato-novel/ -name "*.md" -type f | grep -E "(备份|_fixed|_修复|_质检|_final)" | wc -l

# 建议清理但不自动执行
echo "   ⚠️  建议手动清理重复版本文件"
echo "   📝 示例命令:"
echo "   find tomato-novel/ -name '*备份*.md' -exec rm -f {} \;"
echo "   find tomato-novel/ -name '*_fixed.md' -exec rm -f {} \;"

echo ""
echo "3️⃣ 添加未跟踪的重要文件..."

# 重要配置文件
IMPORTANT_FILES=(
    "feishu_sync_system"
    "git_sync_system"
    "novels"
    "VERSION_CONTROL.md"
    "GIT_WORKFLOW.md"
    "scripts/"
    "memory/"
)

echo "   📄 重要文件列表:"
for file in "${IMPORTANT_FILES[@]}"; do
    if [ -e "$file" ]; then
        echo "   ✅ $file"
        git add "$file"
    else
        echo "   ❌ $file (不存在)"
    fi
done

echo ""
echo "4️⃣ 配置远程仓库..."

# 检查现有远程仓库
echo "   📡 当前远程仓库:"
git remote -v

# 设置远程仓库（Gitea）
GITEA_URL="https://gitea.nevadalice.top:226/liyuchen/tomato-novel-workspace.git"

echo ""
echo "   🚀 添加远程仓库..."
if ! git remote get-url origin >/dev/null 2>&1; then
    echo "   ➕ 添加远程仓库: $GITEA_URL"
    git remote add origin "$GITEA_URL"
else
    echo "   🔄 更新远程仓库URL"
    git remote set-url origin "$GITEA_URL"
fi

echo "   📡 更新后远程仓库:"
git remote -v

echo ""
echo "5️⃣ 提交变更..."

# 生成提交信息
COMMIT_MSG="fix(sync): 修复Git同步问题

- 更新子模块配置
- 添加重要配置文件到版本控制
- 配置远程仓库同步
- 清理重复版本建议"

echo "   📝 提交信息:"
echo "   $COMMIT_MSG"
echo ""

git commit -m "$COMMIT_MSG"

echo ""
echo "6️⃣ 创建备份分支..."

# 创建备份分支
BACKUP_BRANCH="backup-$(date '+%Y%m%d_%H%M%S')"
git branch "$BACKUP_BRANCH"
echo "   📂 创建备份分支: $BACKUP_BRANCH"

echo ""
echo "7️⃣ 推送到远程仓库..."

# 首次推送或强制推送
echo "   🚀 推送到远程..."
git push -u origin master

echo ""
echo "8️⃣ 设置自动同步..."

# 创建自动同步脚本
AUTO_SYNC_SCRIPT="$WORKSPACE_DIR/scripts/git-auto-sync.sh"
cat > "$AUTO_SYNC_SCRIPT" << 'EOF'
#!/bin/bash
# 自动同步脚本

cd /root/.openclaw/workspace

# 拉取远程更新
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🔄 开始自动同步..."
git fetch origin

# 检查是否有冲突
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})

if [ "$LOCAL" = "$REMOTE" ]; then
    echo "    ✅ 本地与远程一致"
elif [ "$LOCAL" = "$BASE" ]; then
    echo "    🔄 拉取远程更新..."
    git pull origin master
    echo "    ✅ 更新完成"
elif [ "$REMOTE" = "$BASE" ]; then
    echo "    🚀 推送本地变更..."
    git push origin master
    echo "    ✅ 推送完成"
else
    echo "    ⚠️  检测到冲突，需要手动处理"
    echo "    📝 请执行: cd /root/.openclaw/workspace && git status"
fi

# 提交本地未提交的变更（如果有）
if ! git diff --quiet; then
    echo "    📝 提交本地变更..."
    git add .
    git commit -m "chore(auto-sync): 自动提交未保存的变更"
    git push origin master
    echo "    ✅ 本地变更已提交"
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🎉 自动同步完成"
EOF

chmod +x "$AUTO_SYNC_SCRIPT"

echo "   🤖 创建自动同步脚本: scripts/git-auto-sync.sh"

echo ""
echo "9️⃣ 创建定时同步任务..."

# 添加到crontab的建议
CRON_JOB="*/30 * * * * cd $WORKSPACE_DIR && ./scripts/git-auto-sync.sh >/dev/null 2>&1"

echo "   ⏰ 建议的定时任务:"
echo "   $CRON_JOB"
echo ""
echo "   📝 添加方法:"
echo "   crontab -e"
echo "   添加行: $CRON_JOB"

echo ""
echo "🔟 清理建议..."

# 清理重复文件建议
echo "   🗑️  重复文件清理建议:"
echo "   # 1. 备份文件"
echo "   find tomato-novel/ -name '*_backup.md' -type f -delete"
echo ""
echo "   # 2. 临时文件"  
echo "   find . -name '*.tmp' -type f -delete"
echo "   find . -name '*.log' -type f -size +10M -delete"
echo ""
echo "   # 3. 清理空目录"
echo "   find . -type d -empty -delete"

echo ""
echo "=================================="
echo "🎉 Git同步问题修复完成！"
echo ""
echo "📋 修复总结:"
echo "   ✅ 子模块更新完成"
echo "   ✅ 重要文件已添加到版本控制"
echo "   ✅ 远程仓库配置完成"
echo "   ✅ 提交本地变更"
echo "   ✅ 创建备份分支: $BACKUP_BRANCH"
echo "   ✅ 自动同步脚本就绪"
echo ""
echo "🚀 下一步建议:"
echo "   1. 手动清理重复文件（建议先备份）"
echo "   2. 设置定时同步任务"
echo "   3. 定期检查同步状态"
echo ""
echo "📞 需要帮助？使用以下命令:"
echo "   ./scripts/git-daily.sh       # 日常管理"
echo "   ./scripts/git-auto-sync.sh   # 手动同步"
echo "   git status                   # 查看状态"