const fs = require('fs');

const file = 'src/modules/book-generator/langgraph-generator.ts';
let content = fs.readFileSync(file, 'utf8');

// 添加断点续传逻辑
const oldCode = `  // 获取当前已生成的字数（用于断点续传）
  let currentWordCount = await getGeneratedWordCount(state.bookId);
  console.log(\`[LangGraph] 当前已生成字数: \${currentWordCount}\`);

  for (const chapterOutline of book.outline.chapters) {`;

const newCode = `  // 获取当前已生成的字数（用于断点续传）
  let currentWordCount = await getGeneratedWordCount(state.bookId);
  console.log(\`[LangGraph] 当前已生成字数: \${currentWordCount}\`);

  // 查询已完成的章节，支持断点续传
  const completedChapterNumbers = new Set<number>();
  for (const ch of book.outline.chapters) {
    const chapter = await bookStore.getChapter(state.bookId, ch.number);
    if (chapter && chapter.status === 'completed') {
      completedChapterNumbers.add(ch.number);
    }
  }
  
  if (completedChapterNumbers.size > 0) {
    console.log(\`[LangGraph] ✅ 跳过 \${completedChapterNumbers.size} 个已完成的章节: [\${Array.from(completedChapterNumbers).join(', ')}]\`);
  }

  for (const chapterOutline of book.outline.chapters) {
    // 跳过已完成的章节
    if (completedChapterNumbers.has(chapterOutline.number)) {
      console.log(\`[LangGraph] 跳过第\${chapterOutline.number}章（已完成）\`);
      continue;
    }`;

content = content.replace(oldCode, newCode);

fs.writeFileSync(file, content, 'utf8');
console.log('✅ 断点续传已添加');
