const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function resetAndSyncGenerate() {
  const bookId = 1;
  
  console.log(`重置并同步生成书籍 ${bookId}...\n`);
  
  // 1. 清空章节数据
  const deleted = await prisma.bookChapter.deleteMany({
    where: { bookId }
  });
  console.log(`已清空: ${deleted.count} 条`);
  
  // 2. 重置状态
  await prisma.book.update({
    where: { id: bookId },
    data: {
      status: 'draft',
      progress: 0,
      errorMsg: null,
    }
  });
  console.log('状态已重置\n');
  
  // 3. 同步调用生成（不使用队列）
  console.log('直接调用生成器（同步模式）...');
  
  const { langGraphGenerator } = require('./src/modules/book-generator');
  
  try {
    const book = await prisma.book.findUnique({ where: { id: bookId } });
    
    await langGraphGenerator.generate(
      bookId.toString(),
      book.description,
      book.bookScale || '130000'
    );
    
    console.log('\n✅ 生成完成！');
    
    const finalBook = await prisma.book.findUnique({ where: { id: bookId } });
    console.log(`最终状态: ${finalBook.status}, 进度: ${finalBook.progress}%`);
    
  } catch (error) {
    console.error('\n❌ 生成失败:', error.message);
    
    await prisma.book.update({
      where: { id: bookId },
      data: {
        status: 'failed',
        errorMsg: error.message,
      }
    });
  }
  
  await prisma.$disconnect();
}

resetAndSyncGenerate().catch(console.error);
