#!/bin/bash

echo "=== 简单重置 inkos ==="

# 1. 停止inkos
echo "1. 停止inkos进程..."
pkill -9 -f "node.*inkos" 2>/dev/null || true
pkill -9 -f "inkos" 2>/dev/null || true
sleep 2

# 2. 备份当前配置
echo "2. 备份配置..."
cp /root/.openclaw/workspace/tomato-novel/inkos.json /root/.openclaw/workspace/tomato-novel/inkos.json.backup.$(date +%Y%m%d_%H%M%S) 2>/dev/null || true

# 3. 创建简化配置（降低审计严格度）
echo "3. 创建简化配置..."
cat > /root/.openclaw/workspace/tomato-novel/inkos_simple.json << 'EOF'
{
  "name": "tomato-novel-simple",
  "version": "0.1.0",
  "language": "zh",
  "llm": {
    "provider": "custom",
    "baseUrl": "https://ark.cn-beijing.volces.com/api/coding/v3",
    "model": "deepseek-v3.2"
  },
  "notify": [],
  "daemon": {
    "schedule": {
      "radarCron": "0 */6 * * *",
      "writeCron": "*/30 * * * *"
    },
    "maxConcurrentBooks": 1
  },
  "quality": {
    "enforcement": "light",  # 改为light模式，降低严格度
    "platform": "tomato",
    "paragraph": {
      "min_length": 20,      # 降低要求
      "max_consecutive_short": 10,
      "max_short_ratio": 0.5
    },
    "golden_points": {
      "min_per_chapter": 1,  # 降低要求
      "keywords": [
        "打脸",
        "升级",
        "收获",
        "碾压",
        "反转"
      ]
    },
    "dialogue": {
      "min_ratio": 0.1,      # 降低要求
      "min_count": 2
    },
    "auto_fix": {
      "enabled": true,
      "merge_paragraphs": true,
      "enhance_golden_points": true,
      "add_dialogue": true
    }
  }
}
EOF

# 4. 使用简化配置启动
echo "4. 使用简化配置启动..."
cd /root/.openclaw/workspace/tomato-novel
cp inkos_simple.json inkos.json

# 5. 清理旧的运行时状态
echo "5. 清理运行时状态..."
RUNTIME_DIR="books/末日重生-开局囤货十亿物资/story/runtime"
STATE_DIR="books/末日重生-开局囤货十亿物资/story/state"

if [ -d "$RUNTIME_DIR" ]; then
    echo "  清理运行时文件..."
    find "$RUNTIME_DIR" -name "chapter-*.json" -type f -mtime +1 -delete 2>/dev/null || true
fi

if [ -d "$STATE_DIR" ]; then
    echo "  重置状态文件..."
    # 只保留current_state.md，删除其他状态文件
    find "$STATE_DIR" -type f ! -name "current_state.md" -delete 2>/dev/null || true
fi

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

# 等待启动
sleep 10

# 7. 检查状态
echo "7. 检查状态..."
if ps aux | grep -q "inkos up" | grep -v grep; then
    PID=$(ps aux | grep "inkos up" | grep -v grep | awk '{print $2}')
    echo "✅ inkos 已启动 (PID: $PID)"
    
    # 等待一下，然后检查状态
    sleep 5
    echo "检查inkos状态..."
    inkos status 2>&1 | head -20
else
    echo "❌ inkos 启动失败"
    echo "查看日志: tail -50 /tmp/inkos_simple_start.log"
fi

echo "=== 重置完成 ==="