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

async function checkBook() {
  const book = await prisma.book.findUnique({ 
    where: { id: 1 }, 
    include: { 
      chapters: { 
        orderBy: [
          { level: 'asc' }, 
          { parentId: 'asc' }, 
          { number: 'asc' }
        ] 
      } 
    } 
  });

  if (!book) {
    console.log('书籍不存在');
    return;
  }

  console.log('=== 书籍信息 ===');
  console.log('ID:', book.id);
  console.log('标题:', book.title);
  console.log('状态:', book.status);
  console.log('进度:', book.progress + '%');
  console.log('总章节数:', book.totalChapters);
  console.log('预估字数:', book.estimatedWords);
  console.log('');

  console.log('=== 大纲结构 (JSON) ===');
  if (book.outlineJson) {
    const outline = JSON.parse(book.outlineJson);
    console.log('主题:', outline.mainTheme);
    console.log('结构逻辑:', outline.structureLogic);
    console.log('章数:', outline.chapters.length);
    
    // 检查是否有节和小节
    outline.chapters.forEach((ch, idx) => {
      console.log(`  第${idx + 1}章: ${ch.title}`);
      if (ch.sections && ch.sections.length > 0) {
        console.log(`    节数: ${ch.sections.length}`);
        ch.sections.forEach((sec, sIdx) => {
          console.log(`    第${sIdx + 1}节: ${sec.title}`);
          if (sec.subsections && sec.subsections.length > 0) {
            console.log(`      小节数: ${sec.subsections.length}`);
          } else {
            console.log(`      ⚠️ 缺少小节`);
          }
        });
      } else {
        console.log(`    ⚠️ 缺少节`);
      }
    });
  } else {
    console.log('⚠️ 无大纲数据');
  }
  console.log('');

  console.log('=== 数据库章节统计 ===');
  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('一级（章）:', level1);
  console.log('二级（节）:', level2);
  console.log('三级（小节）:', level3);
  console.log('总计:', book.chapters.length);
  console.log('');

  console.log('=== 章节详细结构 ===');
  book.chapters.forEach(c => {
    const indent = '  '.repeat(c.level - 1);
    const status = c.status || 'pending';
    console.log(`${indent}L${c.level} #${c.number} ${c.title} [${status}] (ID:${c.id}, Parent:${c.parentId || 'null'})`);
  });

  await prisma.$disconnect();
}

checkBook().catch(console.error);
