#!/bin/bash

echo "=== inkos 优化方案 ==="
echo "基于 inkos 原生能力进行系统性修复"
echo "时间: $(date)"
echo ""

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

# 1. 停止 inkos
echo "1. 停止 inkos 守护进程..."
pkill -f "inkos up" 2>/dev/null
sleep 3
rm -f "$PROJECT_DIR/books/$BOOK_ID/.write.lock" 2>/dev/null
echo "✅ inkos 已停止"
echo ""

# 2. 检查当前状态
echo "2. 检查当前质量状态..."
cd "$PROJECT_DIR"
inkos eval "$BOOK_ID" --json > "/tmp/inkos_eval.json" 2>&1

# 解析结果
TOTAL_CHAPS=$(grep -o '"totalChapters": [0-9]*' /tmp/inkos_eval.json | grep -o '[0-9]*')
QUALITY_SCORE=$(grep -o '"qualityScore": [0-9]*' /tmp/inkos_eval.json | grep -o '[0-9]*')
AUDIT_PASS_RATE=$(grep -o '"auditPassRate": [0-9]*' /tmp/inkos_eval.json | grep -o '[0-9]*')

echo "📊 当前状态:"
echo "   - 总章节: $TOTAL_CHAPS 章"
echo "   - 审核通过率: $AUDIT_PASS_RATE%"
echo "   - 质量评分: $QUALITY_SCORE 分"
echo ""

# 3. 识别需要修复的章节
echo "3. 识别需要修复的章节..."
FAILED_CHAPS=$(grep -o '"status": "audit-failed"' /tmp/inkos_eval.json | wc -l)
echo "   - 审核失败: $FAILED_CHAPS 章"
echo ""

# 4. 创建修复计划
echo "4. 修复计划:"
echo "   A. 关键问题修复 (第1、7、9、11章)"
echo "   B. 次要问题修复 (其他失败章节)"
echo "   C. 预防措施 (优化写作风格)"
echo ""

# 5. 执行关键问题修复
echo "5. 执行关键问题修复..."
for chap in 1 7 9 11; do
    if [ -f "$CHAP_DIR/$(printf "%04d" $chap)_*"*.md ]; then
        echo "🔧 修复第${chap}章..."
        inkos audit "$BOOK_ID" $chap 2>/dev/null | grep -A2 "Summary" | head -2
        echo ""
    fi
done

# 6. 启动优化后的 inkos
echo "6. 启动优化后的 inkos..."
cd "$PROJECT_DIR"
nohup inkos up > /tmp/inkos_optimized.log 2>&1 &
sleep 5

if ps aux | grep "inkos up" | grep -v grep > /dev/null; then
    echo "✅ inkos 已启动 (优化版)"
    PID=$(ps aux | grep "inkos up" | grep -v grep | awk '{print $2}')
    echo "📊 进程信息:"
    echo "   - PID: $PID"
    echo "   - 日志: /tmp/inkos_optimized.log"
else
    echo "❌ inkos 启动失败"
    echo "查看日志: /tmp/inkos_optimized.log"
    exit 1
fi

echo ""
echo "=== 优化完成 ==="
echo "🎯 下一步:"
echo "1. 监控第19章产出质量"
echo "2. 观察审核通过率提升"
echo "3. 建立定期质量检查机制"
echo "4. 准备第1-5章投稿番茄小说"
echo ""
echo "⚠️  注意: 修复基于 inkos 原生能力，不是外部修补"