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

async function checkAllBooks() {
  const books = await prisma.book.findMany({
    orderBy: { id: 'desc' },
    take: 10
  });
  
  console.log('\n📊 所有书籍生成状态检查：\n');
  console.log('=' .repeat(80));
  
  for (const book of books) {
    const chapters = await prisma.bookChapter.findMany({
      where: { bookId: book.id }
    });
    
    const chapterCount = chapters.filter(c => c.level === 1).length;
    const sectionCount = chapters.filter(c => c.level === 2).length;
    const subsectionCount = chapters.filter(c => c.level === 3).length;
    
    const completedContent = chapters.filter(c => c.level === 3 && c.contentStatus === 'completed').length;
    const generatingContent = chapters.filter(c => c.level === 3 && c.contentStatus === 'generating').length;
    const failedContent = chapters.filter(c => c.level === 3 && c.contentStatus === 'failed').length;
    
    const totalWords = chapters.reduce((sum, c) => sum + (c.wordCount || 0), 0);
    
    console.log(`\n📖 Book ID: ${book.id}`);
    console.log(`   标题: ${book.title}`);
    console.log(`   状态: ${book.status}`);
    console.log(`   进度: ${book.progress}%`);
    console.log(`   规模: ${book.bookScale}`);
    console.log(`   大纲: ${chapterCount}章 / ${sectionCount}节 / ${subsectionCount}小节`);
    console.log(`   内容: ${completedContent}完成 / ${generatingContent}生成中 / ${failedContent}失败`);
    console.log(`   总字数: ${totalWords.toLocaleString()}字`);
    
    // 检查是否有异常
    const issues = [];
    if (book.status === 'generating' && book.progress > 90) {
      issues.push('⚠️ 进度超过90%但仍在generating状态');
    }
    if (failedContent > 0) {
      issues.push(`❌ 有${failedContent}个小节生成失败`);
    }
    if (book.status === 'failed') {
      issues.push(`❌ 书籍状态为failed: ${book.error || '未知错误'}`);
    }
    
    if (issues.length > 0) {
      console.log(`   问题:`);
      issues.forEach(issue => console.log(`     ${issue}`));
    } else {
      console.log(`   ✅ 状态正常`);
    }
  }
  
  console.log('\n' + '='.repeat(80));
  console.log('\n检查完成！\n');
  
  await prisma.$disconnect();
}

checkAllBooks().catch(console.error);
