#!/bin/bash

echo "=== 启动 inkos 质量增强版 ==="
echo "开始时间: $(date)"
echo ""

# 1. 检查环境
INKOS_PATH="/usr/bin/inkos"
CONFIG_FILE="/root/.openclaw/workspace/tomato-novel/inkos_quality_config.json"
BOOK_DIR="/root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资"

if [ ! -f "$INKOS_PATH" ]; then
    echo "错误：inkos 未安装"
    exit 1
fi

if [ ! -f "$CONFIG_FILE" ]; then
    echo "错误：配置文件不存在"
    exit 1
fi

if [ ! -d "$BOOK_DIR" ]; then
    echo "错误：书籍目录不存在"
    exit 1
fi

# 2. 备份原始配置
echo "备份原始配置..."
if [ -f "$BOOK_DIR/inkos_config.json" ]; then
    cp "$BOOK_DIR/inkos_config.json" "$BOOK_DIR/inkos_config_backup_$(date +%Y%m%d_%H%M%S).json"
fi

# 3. 应用新配置
echo "应用质量配置..."
cp "$CONFIG_FILE" "$BOOK_DIR/inkos_config.json"

# 4. 启动质量监控
echo "启动质量监控..."
python3 /root/.openclaw/workspace/tomato-novel/scripts/simple_quality_check.py "$BOOK_DIR/chapters/0001_冰点记忆.md" > /tmp/chapter1_quality_check.txt 2>&1 &

# 5. 启动 inkos
echo "启动 inkos..."
cd "$BOOK_DIR" && "$INKOS_PATH" up --config "inkos_config.json" > /tmp/inkos_startup.log 2>&1 &

# 6. 检查启动状态
sleep 5
echo "检查 inkos 进程..."
ps aux | grep "inkos up" | grep -v grep

if [ $? -eq 0 ]; then
    echo "✅ inkos 启动成功"
    echo ""
    echo "=== 质量配置已启用 ==="
    echo "1. 段落结构：最小35字，短段比例<30%"
    echo "2. 爽点密度：每章至少3个爽点"
    echo "3. 对话比例：至少30%对话内容"
    echo "4. 情绪弧线：每章至少2次情绪变化"
    echo "5. 自动修复：启用段落合并、爽点增强"
    echo ""
    echo "监控日志：/tmp/inkos_startup.log"
    echo "质量检查：/tmp/chapter1_quality_check.txt"
else
    echo "❌ inkos 启动失败"
    echo "查看日志：/tmp/inkos_startup.log"
    exit 1
fi

# 7. 创建监控脚本
cat > /root/.openclaw/workspace/inkos_quality_monitor.sh << 'EOF'
#!/bin/bash
echo "=== inkos 质量监控 ==="
echo "时间: $(date)"
echo ""

# 检查进程
if ps aux | grep "inkos up" | grep -v grep > /dev/null; then
    echo "✅ inkos 运行中"
else
    echo "❌ inkos 未运行"
    exit 1
fi

# 检查最新章节
LATEST_CHAPTER=$(ls -t /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/chapters/*.md | head -1)
if [ -f "$LATEST_CHAPTER" ]; then
    CHAPTER_NUM=$(basename "$LATEST_CHAPTER" | cut -d_ -f1)
    CHAPTER_TITLE=$(basename "$LATEST_CHAPTER" .md | cut -d_ -f2-)
    echo "最新章节：第${CHAPTER_NUM}章《${CHAPTER_TITLE}》"
    
    # 运行质量检查
    python3 /root/.openclaw/workspace/tomato-novel/scripts/simple_quality_check.py "$LATEST_CHAPTER" | tail -20
else
    echo "未找到章节文件"
fi
EOF

chmod +x /root/.openclaw/workspace/inkos_quality_monitor.sh

echo ""
echo "=== 启动完成 ==="
echo "结束时间: $(date)"
echo ""
echo "📋 使用说明："
echo "1. 监控状态：bash /root/.openclaw/workspace/inkos_quality_monitor.sh"
echo "2. 停止 inkos：pkill -f 'inkos up'"
echo "3. 查看日志：tail -f /tmp/inkos_startup.log"
echo "4. 质量报告：python3 simple_quality_check.py <章节文件>"
echo ""
echo "⚠️  注意：新配置将强制质量要求，不合格内容将被拒绝或自动修复"