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

async function createMiniBook() {
  console.log('创建迷你测试书籍（2章）...\n');
  
  // 1. 创建书籍
  const bookData = {
    title: 'Python入门教程',
    description: '面向初学者的Python编程基础教程',
    bookScale: '2000', // 最小规模：约2000字
    targetAudience: '编程初学者',
    knowledgeDepth: '入门',
    industry: '教育',
    writingStyle: '通俗易懂',
  };
  
  const postData = JSON.stringify(bookData);
  
  const options = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/book-generator/langgraph/books',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData),
    },
  };
  
  const response = await new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        resolve({
          statusCode: res.statusCode,
          body: JSON.parse(data),
        });
      });
    });
    
    req.on('error', reject);
    req.write(postData);
    req.end();
  });
  
  console.log('书籍创建响应:');
  console.log(JSON.stringify(response.body, null, 2));
  
  if (response.body.code === 0) {
    const bookId = parseInt(response.body.data.book.id);
    console.log(`\n✅ 书籍创建成功！bookId=${bookId}`);
    console.log(`\n访问前端页面：http://localhost:5173/#/pages/book-generator/index?id=${bookId}`);
    console.log('\n开始监控生成进度...\n');
    
    // 2. 监控生成进度
    const prisma = new PrismaClient();
    
    for (let i = 0; i < 30; i++) { // 最多监控30次，每次10秒
      await new Promise(resolve => setTimeout(resolve, 10000)); // 等待10秒
      
      const book = await prisma.book.findUnique({
        where: { id: bookId },
        select: {
          id: true,
          status: true,
          progress: true,
          errorMsg: true,
        }
      });
      
      const chapters = await prisma.bookChapter.count({ where: { bookId, level: 1 } });
      const sections = await prisma.bookChapter.count({ where: { bookId, level: 2 } });
      const subsections = await prisma.bookChapter.count({ where: { bookId, level: 3 } });
      const completedContent = await prisma.bookChapter.count({ 
        where: { bookId, level: 3, contentStatus: 'completed' } 
      });
      
      console.log(`[${new Date().toLocaleTimeString()}] 状态: ${book.status}, 进度: ${book.progress}%, ` +
                  `章: ${chapters}, 节: ${sections}, 小节: ${subsections}, 已完成内容: ${completedContent}`);
      
      if (book.errorMsg) {
        console.log(`  ❌ 错误: ${book.errorMsg}`);
        break;
      }
      
      if (book.status === 'completed') {
        console.log('\n🎉 生成完成！');
        
        // 显示生成的内容
        const firstContent = await prisma.bookChapter.findFirst({
          where: { bookId, level: 3, contentStatus: 'completed' },
          select: { title: true, content: true, wordCount: true }
        });
        
        if (firstContent) {
          console.log(`\n📝 第一个完成的小节: ${firstContent.title}`);
          console.log(`字数: ${firstContent.wordCount}`);
          console.log(`内容预览:\n${firstContent.content.substring(0, 500)}...`);
        }
        
        break;
      }
    }
    
    await prisma.$disconnect();
  }
}

createMiniBook().catch(console.error);
