const fs = require('fs');

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

// 找到并替换整个小节查询部分
const startMarker = '  // 从数据库获取所有小节（level=3）';
const endMarker = '  // 构建父节点映射，便于获取上下文';

const startIdx = content.indexOf(startMarker);
const endIdx = content.indexOf(endMarker);

if (startIdx === -1 || endIdx === -1) {
  console.log('❌ 未找到标记');
  process.exit(1);
}

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.slice(0, startIdx) + newCode + content.slice(endIdx);

// 修改进度计算
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('✅ 断点续传支持已添加');
