#!/bin/bash

echo "=== 应用修复文件 ==="
echo "开始时间: $(date)"
echo ""

CHAPTERS_DIR="/root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/chapters"

echo "📁 目录: $CHAPTERS_DIR"
echo ""

# 1. 备份所有原始文件
echo "1. 备份所有原始文件..."
backup_dir="$CHAPTERS_DIR/backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
for file in "$CHAPTERS_DIR"/*.md; do
    if [[ -f "$file" && ! "$file" =~ _fixed\.md$ ]]; then
        cp "$file" "$backup_dir/"
    fi
done
echo "✅ 备份完成: $backup_dir"
echo ""

# 2. 替换修复文件
echo "2. 替换修复文件..."
fixed_files=0
for fixed_file in "$CHAPTERS_DIR"/*_fixed.md; do
    if [[ -f "$fixed_file" ]]; then
        # 提取原始文件名
        base_name=$(basename "$fixed_file")
        original_file="${base_name%_fixed.md}.md"
        # 替换文件
        cp "$fixed_file" "$CHAPTERS_DIR/$original_file"
        fixed_files=$((fixed_files + 1))
        echo "   ✅ 替换: $original_file"
    fi
done
echo ""
echo "✅ 总共替换了 $fixed_files 个文件"
echo ""

# 3. 生成报告
echo "3. 生成修复报告..."
echo "### 修复总结" > /tmp/fix_report.md
echo "**时间:** $(date)" >> /tmp/fix_report.md
echo "**修复章节数:** $fixed_files" >> /tmp/fix_report.md
echo "" >> /tmp/fix_report.md
echo "**修复文件列表:**" >> /tmp/fix报告.md
for fixed_file in "$CHAPTERS_DIR"/*_fixed.md; do
    if [[ -f "$fixed_file" ]]; then

        echo "- $(basename "$fixed_file")" >> /tmp/fix_report.md

    fi

done

echo "" >> /tmp/fix_report.md

echo "**备份位置:** $backup_dir" >> /tmp/fix_report.md

echo "**下一步建议:**" >> /tmp/fix_report.md

echo "1. 重新启动 inkos" >> /tmp/fix_report.md

echo "2. 监控章节质量" >> /tmp/fix_report.md

echo "3. 调整写作参数" >> /fix_report.md

echo "" 

echo "=== 修复应用完成 ==="

echo "结束时间: $(date)" 
