#!/bin/bash

echo "=== 完全干净重启 inkos ==="

echo "1. 停止所有 inkos 相关进程..."
pkill -9 -f "node.*inkos" 2>/dev/null || true
pkill -9 -f "inkos" 2>/dev/null || true
pkill -9 -f "inkos_monitor" 2>/dev/null || true
sleep 2

echo "2. 清理所有 inkos 运行时文件..."
rm -f /tmp/inkos*.lock 2>/dev/null || true
rm -f /tmp/node*.pid 2>/dev/null || true

# 清理inkos项目中的运行时文件
rm -rf /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/story/runtime/* 2>/dev/null || true
rm -rf /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/story/state/* 2>/dev/null || true
rm -rf /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/story/audit/* 2>/dev/null || true

echo "3. 创建最简单的 inkos 配置..."
cat > /root/.openclaw/workspace/tomato-novel/inkos.json << 'EOF'
{
  "name": "tomato-novel-clean-start",
  "version": "0.1.0",
  "language": "zh",
  "llm": {
    "provider": "custom",
    "baseUrl": "https://ark.cn-beijing.volces.com/api/coding/v3",
    "model": "deepseek-v3.2"
  },
  "daemon": {
    "schedule": {
      "writeCron": "0 */1 * * *"
    },
    "maxConcurrentBooks": 1
  },
  "quality": {
    "enforcement": "none"
  }
}
EOF

echo "4. 删除inkos的PID文件..."
rm -f /root/.openclaw/workspace/tomato-novel/inkos.pid 2>/dev/null || true

echo "5. 启动inkos守护进程..."
cd /root/.openclaw/workspace/tomato-novel

# 确保没有任何残留进程
ps aux | grep "inkos up" | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null || true

# 等待一段时间
sleep 3

# 启动新的inkos进程
nohup inkos up > /tmp/inkos_clean_start.log 2>&1 &

# 等待启动
sleep 10

echo "6. 检查启动状态..."
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)"
    
    # 等待inkos初始化完成
    echo "等待inkos初始化..."

    sleep 15

    # 测试inkos创作

    echo "测试inkos创作..."

    result=$(timeout 20 inkos draft 末日重生-开局囤货十亿物资 2>&1 | head -20)

    if echo "$result" | grep -q "Writing draft for"; then

        echo "✅ inkos 创作测试成功!"

        echo "inkos状态:"

        inkos status 2>&1 | head -20

    else

        echo "❌ inkos 创作测试失败"

        echo "错误信息:"

        echo "$result"

    fi

else

    echo "❌ inkos 启动失败"

    echo "查看日志: tail -50 /tmp/inkos_clean_start.log"

fi

echo "=== 完成 ==="