const fs = require('fs');

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

// 替换第1处：创建书籍
content = content.replace(
  `    // 启动 LangGraph 生成（异步，自动完成：大纲→章节→前言/后记）
    langGraphGenerator.generate(
      book.id,
      body.description,
      bookScale
    ).catch(err => {
      console.error('[LangGraph] 生成失败:', err);
    });`,
  `    // 将生成任务加入队列（由队列处理器异步执行）
    const jobId = await queueService.addBookGenerationTask({
      bookId: book.id,
      topic: body.description,
      bookScale,
    });
    
    console.log(\`[LangGraph] 生成任务已加入队列: bookId=\${book.id}, jobId=\${jobId}\`);`
);

// 替换第2处：重新生成
content = content.replace(
  `    // 启动 LangGraph 生成
    langGraphGenerator.generate(
      bookId,
      book.description,
      bookScale
    ).catch(err => {
      console.error('[LangGraph] 生成失败:', err);
    });`,
  `    // 将生成任务加入队列
    const jobId = await queueService.addBookGenerationTask({
      bookId,
      topic: book.description,
      bookScale,
    });
    
    console.log(\`[LangGraph] 重新生成任务已加入队列: bookId=\${bookId}, jobId=\${jobId}\`);`
);

// 替换第3处：续生成
content = content.replace(
  `    // 重新启动生成（只生成 pending 状态的小节）
    langGraphGenerator.generate(
      bookId,
      book.description || book.title,
      book.bookScale || '130000'
    ).catch(err => {
      console.error('[LangGraph] 续生成失败:', err);
    });`,
  `    // 将续生成任务加入队列
    const jobId = await queueService.addBookGenerationTask({
      bookId,
      topic: book.description || book.title,
      bookScale: book.bookScale || '130000',
    });
    
    console.log(\`[LangGraph] 续生成任务已加入队列: bookId=\${bookId}, jobId=\${jobId}\`);`
);

fs.writeFileSync(file, content, 'utf8');
console.log('✅ 控制器已改为使用队列');
