const fs = require('fs');

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

// 添加断点续传：筛选未完成的小节
const oldCode = `  // 从数据库获取所有小节（level=3）
  const subsections = await prisma.bookChapter.findMany({
    where: { bookId: bookIdNum, level: 3 },
    orderBy: [
      { parentId: 'asc' },  // 先按父节点排序
      { number: 'asc' }
    ],
    include: {
      // 获取父节的信息
      parent: {
        include: {
          // 获取父章的信息
          parent: true
        }
      }
    }
  });

  if (subsections.length === 0) {
    console.log('[LangGraph] 没有小节，跳过内容生成');
    return { finished: true, progress: 90 };
  }`;

const newCode = `  // 从数据库获取所有小节（level=3）
  const allSubsections = await prisma.bookChapter.findMany({
    where: { bookId: bookIdNum, level: 3 },
    orderBy: [
      { parentId: 'asc' },  // 先按父节点排序
      { number: 'asc' }
    ],
    include: {
      // 获取父节的信息
      parent: {
        include: {
          // 获取父章的信息
          parent: true
        }
      }
    }
  });

  if (allSubsections.length === 0) {
    console.log('[LangGraph] 没有小节，跳过内容生成');
    return { finished: true, progress: 90 };
  }

  // 筛选出未完成的小节（pending 或 failed），支持断点续传
  const subsections = allSubsections.filter(s => s.status !== 'completed');
  const completedCount = allSubsections.length - subsections.length;
  
  if (completedCount > 0) {
    console.log(\`[LangGraph] ✅ 跳过 \${completedCount} 个已完成的小节，待生成 \${subsections.length} 个\`);
  }
  
  if (subsections.length === 0) {
    console.log('[LangGraph] ✅ 所有小节已完成');
    return { finished: true, progress: 95 };
  }`;

content = content.replace(oldCode, newCode);

// 修改进度计算：从已完成的数量开始
content = content.replace(
  /const totalSubsections = subsections\.length;\s+let completedSubsections = 0;/,
  `const totalSubsections = allSubsections.length;
  let completedSubsections = completedCount; // 从已完成的数量开始`
);

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