const http = require('http');

async function testGenerateAPI() {
  const bookId = 2;
  
  console.log(`测试 bookId=${bookId} 的生成API...\n`);
  
  // 1. 先重置状态
  console.log('步骤1: 重置书籍状态...');
  const { PrismaClient } = require('@prisma/client');
  const prisma = new PrismaClient();
  
  await prisma.book.update({
    where: { id: bookId },
    data: {
      status: 'draft',
      progress: 0,
      errorMsg: null,
    }
  });
  console.log('✅ 状态已重置\n');
  
  // 2. 调用生成API
  console.log('步骤2: 调用生成API...');
  
  const postData = JSON.stringify({});
  
  const options = {
    hostname: 'localhost',
    port: 3000,
    path: `/api/book-generator/langgraph/books/${bookId}/generate`,
    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('\nAPI响应:');
  console.log(`状态码: ${response.statusCode}`);
  console.log(`响应体: ${JSON.stringify(response.body, null, 2)}`);
  
  // 3. 等待5秒后检查状态
  console.log('\n步骤3: 等待5秒后检查状态...');
  await new Promise(resolve => setTimeout(resolve, 5000));
  
  const book = await prisma.book.findUnique({
    where: { id: bookId },
    select: { id: true, status: true, progress: true, errorMsg: true }
  });
  
  console.log('\n当前状态:');
  console.log(JSON.stringify(book, null, 2));
  
  await prisma.$disconnect();
  
  console.log('\n✅ 测试完成！');
  console.log('\n请刷新前端页面查看：http://localhost:5173/#/pages/book-generator/index?id=2');
}

testGenerateAPI().catch(console.error);
