#!/bin/bash

echo "=== 启动 inkos (最终版本) ==="
echo "时间: $(date)"
echo ""

PROJECT_DIR="/root/.openclaw/workspace/tomato-novel"
BOOK_DIR="$PROJECT_DIR/books/末日重生-开局囤货十亿物资"
CONFIG_FILE="$BOOK_DIR/inkos_config.json"

# 1. 进入项目目录
cd "$PROJECT_DIR" || {
    echo "❌ 错误：无法进入项目目录"
    exit 1
}

# 2. 检查项目文件
if [ ! -f "inkos.json" ]; then
    echo "❌ 错误：inkos.json 不存在"
    exit 1
fi

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

echo "✅ 项目目录: $PROJECT_DIR"
echo "✅ 配置文件: $CONFIG_FILE"
echo "✅ 书籍目录: $BOOK_DIR"
echo ""

# 3. 应用质量配置（合并到 inkos.json）
echo "3. 应用质量配置..."
# 检查是否需要合并配置
if ! grep -q "quality" inkos.json; then
    echo "⚠️  将在 inkos.json 中添加质量配置..."
    # 备份原始配置
    cp inkos.json inkos.json.backup.$(date +%Y%m%d_%H%M%S)
    
    # 简单添加质量配置节
    python3 -c "
import json
import sys

# 读取 inkos.json
with open('inkos.json', 'r', encoding='utf-8') as f:
    config = json.load(f)

# 添加质量配置
config['quality'] = {
    'enforcement': 'strict',
    'platform': 'tomato',
    'paragraph': {
        'min_length': 35,
        'max_consecutive_short': 3,
        'max_short_ratio': 0.3
    },
    'golden_points': {
        'min_per_chapter': 3,
        'keywords': ['打脸', '升级', '收获', '碾压', '反转', '爽点', '优势', '先知', '重生']
    },
    'dialogue': {
        'min_ratio': 0.3,
        'min_count': 5
    },
    'auto_fix': {
        'enabled': True,
        'merge_paragraphs': True,
        'enhance_golden_points': True,
        'add_dialogue': True
    }
}

# 写回文件
with open('inkos.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

print('✅ 质量配置已添加到 inkos.json')
" 2>/dev/null || echo "⚠️  Python 配置合并失败，使用现有配置"
fi

echo "✅ 配置准备完成"
echo ""

# 4. 启动 inkos
echo "4. 启动 inkos..."
nohup inkos up > /tmp/inkos_final_startup.log 2>&1 &

sleep 5

# 5. 检查进程
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 启动成功"
    echo "✅ PID: $PID"
    echo "✅ 日志: /tmp/inkos_final_startup.log"
    
    # 显示启动日志
    echo ""
    echo "📝 启动日志摘要:"
    tail -10 /tmp/inkos_final_startup.log
else
    echo "❌ inkos 启动失败"
    echo "查看完整日志: /tmp/inkos_final_startup.log"
    tail -20 /tmp/inkos_final_startup.log
    exit 1
fi

echo ""
echo "=== inkos 质量增强版已启动 ==="
echo "📋 配置摘要:"
echo "   - 项目: tomato-novel"
echo "   - 书籍: 末日重生-开局囤货十亿物资"
echo "   - 平台: 番茄小说 (tomato)"
echo "   - 质量: 严格模式 (strict)"
echo "   - 自动修复: 启用"
echo ""
echo "🎯 监控命令: bash /root/.openclaw/workspace/inkos_quality_monitor.sh"
echo "🛑 停止命令: pkill -f 'inkos up'"
echo "📊 质量检查: python3 /root/.openclaw/workspace/tomato-novel/scripts/simple_quality_check.py <章节文件>"
echo ""
echo "⚠️  注意：质量配置将强制执行，不合格内容将被拒绝或自动修复"