#!/bin/bash

echo "=== 第19章产出监控 ==="
echo "开始时间: $(date)"
echo "监控: 第19章《钢渣》创作完成状态"
echo ""

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

echo "📊 监控参数:"
echo "   - 监控目录: $CHAP_DIR"
echo "   - 日志文件: $LOG_FILE"
echo "   - 最长等待: $MAX_WAIT_MINUTES 分钟"
echo "   - 检查间隔: $CHECK_INTERVAL 秒"
echo ""

echo "🔍 当前状态:"
if ps aux | grep "inkos up" | grep -v grep > /dev/null; then
    PID=$(ps aux | grep "inkos up" | grep -v grep | awk '{print $2}')
    echo "   ✅ inkos 运行中 (PID: $PID)"
else
    echo "   ❌ inkos 未运行"
    exit 1
fi

# 检查是否已有第19章
if ls "$CHAP_DIR/0019_"*.md 2>/dev/null; then
    echo "   ✅ 第19章已存在"
    exit 0
else
    echo "   ⏳ 第19章创作中..."
fi

echo ""
echo "📝 日志摘要:"
tail -5 "$LOG_FILE" 2>/dev/null || echo "   日志文件不存在"
echo ""

# 开始监控
echo "🔄 开始监控..."
for ((i=1; i<=$((MAX_WAIT_MINUTES*60/CHECK_INTERVAL)); i++)); do
    # 检查第19章是否产出
    if ls "$CHAP_DIR/0019_"*.md 2>/dev/null; then
        CHAPTER_FILE=$(ls -t "$CHAP_DIR/0019_"*.md 2>/dev/null | head -1)
        CHAPTER_NAME=$(basename "$CHAPTER_FILE")
        CHAPTER_SIZE=$(wc -c < "$CHAPTER_FILE")
        
        echo ""
        echo "🎉 第19章产出完成！"
        echo "📊 产出信息:"
        echo "   - 文件名: $CHAPTER_NAME"
        echo "   - 文件大小: $CHAPTER_SIZE 字符"
        echo "   - 产出时间: $(date)"
        echo ""
        
        # 立即质量检查
        echo "🔍 立即质量检查:"
        python3 /root/.openclaw/workspace/tomato-novel/scripts/simple_quality_check.py "$CHAPTER_FILE" | grep -E "段落分析|爽点分析|对话分析|发现问题|修复建议"
        
        exit 0
    fi
    
    # 检查日志
    echo -n "."
    
    # 每隔5次检查显示一次日志
    if [ $((i % 5)) -eq 0 ]; then
        echo ""
        tail -3 "$LOG_FILE" 2>/dev/null | grep -v "^$" || true
    fi
    
    sleep $CHECK_INTERVAL
done

echo ""
echo "⏰ 监控超时: 等待${MAX_WAIT_MINUTES}分钟未产出第19章"
echo "📝 最后日志:"
tail -10 "$LOG_FILE" 2>/dev/null || echo "   无日志记录"

exit 1