#!/bin/bash

echo "=== 检查第2-14章质量 ==="
echo "开始时间: $(date)"
echo ""

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

# 创建汇总报告
SUMMARY_FILE="quality_summary_ch2_14_$(date +%Y%m%d_%H%M%S).md"
echo "# 第2-14章质量检查汇总" > $SUMMARY_FILE
echo "**检查时间：** $(date)" >> $SUMMARY_FILE
echo "" >> $SUMMARY_FILE

# 检查每个章节
for i in {2..14}; do
    CHAPTER_NUM=$(printf "%04d" $i)
    CHAPTER_FILE="${CHAPTERS_DIR}/${CHAPTER_NUM}_*.md"
    
    echo "检查第${i}章..."
    
    # 查找实际文件
    ACTUAL_FILE=$(ls $CHAPTER_FILE 2>/dev/null | head -1)
    
    if [ -f "$ACTUAL_FILE" ]; then
        # 提取章节标题
        CHAPTER_TITLE=$(basename "$ACTUAL_FILE" .md | cut -d_ -f2-)
        
        echo "## 第${i}章: ${CHAPTER_TITLE}" >> $SUMMARY_FILE
        echo "**文件：** $(basename $ACTUAL_FILE)" >> $SUMMARY_FILE
        
        # 运行质量检查
        python3 "$QUALITY_CHECK" "$ACTUAL_FILE" > /tmp/ch${i}_quality.txt 2>&1
        
        # 提取关键信息
        PARA_INFO=$(grep "总段落数" /tmp/ch${i}_quality.txt)
        SHORT_RATIO=$(grep "短段落比例" /tmp/ch${i}_quality.txt)
        GOLDEN_POINTS=$(grep "找到爽点关键词" /tmp/ch${i}_quality.txt)
        DIALOGUE_RATIO=$(grep "对话比例" /tmp/ch${i}_quality.txt)
        PROBLEMS=$(sed -n '/问题识别：/,/修复建议：/p' /tmp/ch${i}_quality.txt | head -20)
        
        echo "### 📊 质量指标" >> $SUMMARY_FILE
        echo "- $PARA_INFO" | sed 's/总段落数：/段落总数：/' >> $SUMMARY_FILE
        echo "- $SHORT_RATIO" >> $SUMMARY_FILE
        echo "- $GOLDEN_POINTS" >> $SUMMARY_FILE
        echo "- $DIALOGUE_RATIO" >> $SUMMARY_FILE
        
        # 检查问题
        if echo "$PROBLEMS" | grep -q "发现问题"; then
            echo "### ⚠️ 发现问题" >> $SUMMARY_FILE
            echo '```' >> $SUMMARY_FILE
            echo "$PROBLEMS" | sed -n '/发现问题：/,/修复建议：/p' | head -10 >> $SUMMARY_FILE
            echo '```' >> $SUMMARY_FILE
        else
            echo "### ✅ 未发现严重问题" >> $SUMMARY_FILE
        fi
        
        echo "" >> $SUMMARY_FILE
        echo "---" >> $SUMMARY_FILE
        echo "" >> $SUMMARY_FILE
        
    else
        echo "第${i}章文件不存在" >> $SUMMARY_FILE
        echo "" >> $SUMMARY_FILE
    fi
done

# 生成摘要
echo "## 📋 总体评估" >> $SUMMARY_FILE
echo "" >> $SUMMARY_FILE
echo "**检查章节范围：** 第2-14章" >> $SUMMARY_FILE
echo "**检查时间：** $(date)" >> $SUMMARY_FILE
echo "**检查工具：** simple_quality_check.py" >> $SUMMARY_FILE
echo "" >> $SUMMARY_FILE
echo "### 🎯 建议操作" >> $SUMMARY_FILE
echo "1. 修复问题严重的章节" >> $SUMMARY_FILE
echo "2. 优化段落结构" >> $SUMMARY_FILE
echo "3. 增加爽点密度" >> $SUMMARY_FILE
echo "4. 提高对话比例" >> $SUMMARY_FILE

echo ""
echo "检查完成！"
echo "汇总报告已保存到: $SUMMARY_FILE"