#!/bin/bash

echo "=== 第19章专项监控 ==="
echo "时间: $(date)"
echo "监控目标: 第19章 spot-fix 修复完成状态"
echo ""

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

# 检查 inkos 状态
echo "🔧 inkos 状态检查:"
if ps aux | grep "inkos up" | grep -v grep > /dev/null; then
    PID=$(ps aux | grep "inkos up" | grep -v grep | awk '{print $2}')
    CPU=$(ps -p $PID -o %cpu --no-headers 2>/dev/null || echo "0")
    MEM=$(ps -p $PID -o %mem --no-headers 2>/dev/null || echo "0")
    echo "✅ 运行中 (PID: $PID)"
    echo "   - CPU使用: ${CPU}%"
    echo "   - 内存使用: ${MEM}%"
else
    echo "❌ 未运行"
    exit 1
fi
echo ""

# 检查第19章是否产出
echo "📖 第19章产出状态:"
if ls "$CHAP_DIR/0019_"*.md 2>/dev/null >/dev/null; then
    CHAP_FILE=$(ls -t "$CHAP_DIR/0019_"*.md 2>/dev/null | head -1)
    CHAP_SIZE=$(wc -c < "$CHAP_FILE" 2>/dev/null || echo 0)
    echo "✅ 已产出!"
    echo "   - 文件名: $(basename "$CHAP_FILE")"
    echo "   - 文件大小: $CHAP_SIZE 字符"
    echo "   - 产出时间: $(stat -c %y "$CHAP_FILE" 2>/dev/null || echo "unknown")"
    exit 0
else
    echo "⏳ 尚未产出 (spot-fix 修复中)"
fi
echo ""

# 分析日志状态
echo "📝 日志分析:"
if [ -f "$LOG_FILE" ]; then
    # 获取最后30行日志
    tail -30 "$LOG_FILE" | grep -E "INFO.*第19章|WARN.*第19章|ERROR.*第19章|spot-fix|审计|修复|字数归一化" | tail -10 | while read -r line; do
        echo "   $line"
    done
    
    # 检查修复进度
    echo ""
    echo "🔍 修复进度分析:"
    
    # 检查是否有错误被修复
    if grep -q "WARN.*第19章" "$LOG_FILE"; then
        ERROR_COUNT=$(grep -c "WARN.*第19章" "$LOG_FILE")
        echo "   ⚠️  检测到 $ERROR_COUNT 个警告/错误"
    else
        echo "   ✅ 无警告/错误 (可能已修复)"
    fi
    
    # 检查 spot-fix 状态
    if grep -q "spot-fix" "$LOG_FILE"; then
        echo "   🔧 spot-fix 修复正在进行"
    else
        echo "   ✅ spot-fix 可能已完成"
    fi
    
    # 检查字数归一化
    if grep -q "字数归一化.*第19章" "$LOG_FILE"; then
        WORD_NORMS=$(grep "字数归一化.*第19章" "$LOG_FILE" | tail -2)
        echo "   📊 字数归一化:"
        echo "   $WORD_NORMS" | while read -r norm; do
            echo "      $norm"
        done
    fi
else
    echo "   📝 日志文件不存在"
fi
echo ""

# 检查创作流程状态
echo "🔄 创作流程状态:"
if grep -q "阶段：审计草稿" "$LOG_FILE"; then
    echo "   🔄 审计阶段进行中"
elif grep -q "阶段：自动修复关键问题" "$LOG_FILE"; then
    echo "   🔧 自动修复进行中"
elif grep -q "阶段：准备章节输入" "$LOG_FILE"; then
    echo "   📝 准备阶段进行中"
else
    echo "   ⏳ 未知阶段"
fi
echo ""

# 基于日志的预计时间
echo "⏰ 预计完成时间:"
LOG_TIME=$(tail -1 "$LOG_FILE" | grep -o "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" || echo "unknown")
if [ "$LOG_TIME" != "unknown" ]; then
    echo "   📅 最近日志时间: $LOG_TIME"
    echo "   ⏳ 预计还需: 5-10分钟 (基于深度修复流程)"
else
    echo "   ⏳ 预计: 10分钟内完成"
fi
echo ""

echo "=== 监控建议 ==="
echo "1. 继续等待 spot-fix 完成"
echo "2. 检查日志了解详细修复进度"
echo "3. 产出后立即进行质量验证"
echo "4. 验证风格导入效果"
echo ""
echo "📊 当前流程: 创作 → 检测 → 修复 → 审计 → 产出"