#!/bin/bash

echo "=== inkos 问题终极解决方案 ==="
echo "此方案将:"
echo "1. 备份现有章节文件"
echo "2. 创建全新的inkos项目"
echo "3. 导入现有章节"
echo "4. 测试创作功能"
echo ""

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

# 2. 备份章节文件
echo "2. 备份章节文件..."
BACKUP_DIR="/root/.openclaw/workspace/backups/chapters_backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

# 备份原始章节文件
CHAPTERS_SOURCE="/root/.openclaw/workspace/tomato-novel/tomato-novel/books/末日重生-开局囤货十亿物资/chapters"
if [ -d "$CHAPTERS_SOURCE" ]; then
    cp -r "$CHAPTERS_SOURCE" "$BACKUP_DIR/"
    echo "   章节文件已备份到: $BACKUP_DIR"
fi

# 3. 清理旧的inkos数据
echo "3. 清理旧的inkos数据..."
rm -rf /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资/story 2>/dev/null || true
rm -rf /root/.openclaw/workspace/tomato-novel/books/末日重生-开局囤货十亿物资 2>/dev/null || true

# 4. 创建最简单的inkos配置
echo "4. 创建最简单的inkos配置..."
cat > /root/.openclaw/workspace/tomato-novel/inkos_ultimate.json << 'EOF'
{
  "name": "tomato-novel-ultimate",
  "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

cp /root/.openclaw/workspace/tomato-novel/inkos_ultimate.json /root/.openclaw/workspace/tomato-novel/inkos.json

# 5. 创建新的小说项目
echo "5. 创建新的小说项目..."
cd /root/.openclaw/workspace/tomato-novel

# 创建书籍目录结构
BOOK_DIR="books/末日重生-开局囤货十亿物资"
mkdir -p "$BOOK_DIR/chapters"
mkdir -p "$BOOK_DIR/story/state"
mkdir -p "$BOOK_DIR/story/runtime"

# 创建基本的book.json
cat > "$BOOK_DIR/book.json" << 'EOF'
{
  "id": "末日重生-开局囤货十亿物资",
  "title": "末日重生：开局囤货十亿物资",
  "platform": "tomato",
  "genre": "urban",
  "language": "zh",
  "targetChapters": 200,
  "currentChapter": 143,
  "status": "active",
  "createdAt": "2026-04-06T21:55:00.000Z",
  "updatedAt": "2026-04-06T21:55:00.000Z"
}
EOF

# 6. 复制章节文件
echo "6. 复制章节文件..."
if [ -d "$CHAPTERS_SOURCE" ]; then
    # 只复制第136-143章，避免任何数据错误
    for chapter in {136..143}; do
        chapter_file=$(find "$CHAPTERS_SOURCE" -name "${chapter}_*.md" | head -1)
        if [ -f "$chapter_file" ]; then
            cp "$chapter_file" "$BOOK_DIR/chapters/"
            echo "   复制: $(basename "$chapter_file")"
        fi
    done
    
    # 复制最新的index.json
    if [ -f "$CHAPTERS_SOURCE/index.json" ]; then
        cp "$CHAPTERS_SOURCE/index.json" "$BOOK_DIR/chapters/"
        echo "   复制: index.json"
    fi
fi

# 7. 创建简单的index.json（只包含136-143章）
echo "7. 创建简单的index.json..."
cat > "$BOOK_DIR/chapters/index_simple.json" << 'EOF'
[
  {
    "number": 136,
    "title": "危机升级",
    "status": "ready-for-review",
    "wordCount": 2442
  },
  {
    "number": 137,
    "title": "暗流涌动",
    "status": "ready-for-review",
    "wordCount": 3494
  },
  {
    "number": 138,
    "title": "夜色酒吧",
    "status": "ready-for-review",
    "wordCount": 3467
  },
  {
    "number": 139,
    "title": "眼镜来访",
    "status": "ready-for-review",
    "wordCount": 3345
  },
  {
    "number": 140,
    "title": "资金链危机",
    "status": "ready-for-review",
    "wordCount": 2626
  },
  {
    "number": 141,
    "title": "眼镜的选择",
    "status": "ready-for-review",
    "wordCount": 2291
  },
  {
    "number": 142,
    "title": "老火车站的交易",
    "status": "ready-for-review",
    "wordCount": 2580
  },
  {
    "number": 143,
    "title": "刀疤刘的行动",
    "status": "ready-for-review",
    "wordCount": 2102
  }
]
EOF

cp "$BOOK_DIR/chapters/index_simple.json" "$BOOK_DIR/chapters/index.json"

# 8. 启动inkos
echo "8. 启动inkos守护进程..."
nohup inkos up > /tmp/inkos_ultimate_start.log 2>&1 &

sleep 10

# 9. 检查启动状态
echo "9. 检查启动状态..."
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 "10. 检查inkos状态..."
    inkos status 2>&1
    
    echo ""
    echo "11. 测试创作第144章..."
    echo "正在创作，请等待30-60秒..."
    
    # 尝试创作下一章
    result=$(timeout 30 inkos draft 末日重生-开局囤货十亿物资 2>&1 | head -30)
    
    if echo "$result" | grep -q "Writing draft for"; then
        echo "✅ inkos 创作测试成功！"
        echo "inkos现在应该可以正常创作了。"
    else
        echo "❌ inkos 创作测试失败"
        echo "错误信息:"
        echo "$result"
        echo ""
        echo "查看详细日志: tail -50 /tmp/inkos_ultimate_start.log"
    fi
else
    echo "❌ inkos 启动失败"
    echo "查看日志: tail -50 /tmp/inkos_ultimate_start.log"
fi

echo ""
echo "=== 解决方案完成 ==="
echo "备份位置: $BACKUP_DIR"
echo "如果创作成功，inkos将继续自动创作第144章及后续章节。"