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

async function monitor() {
  console.log('开始监控书籍 #3 生成进度...\n');
  
  for (let i = 0; i < 120; i++) {
    const book = await prisma.book.findUnique({ 
      where: { id: 3 },
      include: { chapters: true }
    });
    
    if (!book) {
      console.log('书籍不存在');
      break;
    }
    
    const level1 = book.chapters.filter(c => c.level === 1).length;
    const level2 = book.chapters.filter(c => c.level === 2).length;
    const level3 = book.chapters.filter(c => c.level === 3).length;
    
    console.log(`[${new Date().toLocaleTimeString()}] 状态: ${book.status.padEnd(12)} | 进度: ${book.progress.toString().padStart(3)}% | 章: ${level1} | 节: ${level2} | 小节: ${level3} | 总计: ${book.chapters.length}`);
    
    if (book.status === 'completed' || book.status === 'failed') {
      console.log('\n' + '='.repeat(80));
      console.log('✅ 生成完成！');
      console.log('='.repeat(80));
      console.log('最终状态:', book.status);
      console.log('最终进度:', book.progress + '%');
      console.log('章节统计:', { level1, level2, level3, total: book.chapters.length });
      
      if (level1 > 0) {
        console.log('\n章节结构:');
        book.chapters.filter(c => c.level === 1).forEach(c => {
          console.log(`  第${c.number}章: ${c.title} [${c.status}] (ID:${c.id})`);
          const sections = book.chapters.filter(s => s.parentId === c.id);
          sections.forEach(s => {
            console.log(`    第${s.number}节: ${s.title} [${s.status}] (ID:${s.id})`);
            const subsections = book.chapters.filter(ss => ss.parentId === s.id);
            subsections.forEach(ss => {
              console.log(`      第${ss.number}小节: ${ss.title} [${ss.status}]`);
            });
          });
        });
      }
      break;
    }
    
    await new Promise(resolve => setTimeout(resolve, 3000));
  }
  
  await prisma.$disconnect();
}

monitor().catch(console.error);
