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

async function testFullAudioGeneration() {
  const bookId = 5; // Git入门（最小，章节少）
  
  console.log('\n🎵 开始完整音频生成测试\n');
  console.log('=' .repeat(60));
  
  // 步骤1：记录测试前的状态
  console.log('\n📊 步骤1：记录测试前状态\n');
  
  const beforeBooks = await prisma.book.count();
  const beforeAudioRecords = await prisma.audioRecord.count({
    where: { userId: 1 }
  });
  const beforeSubsectionsWithAudio = await prisma.bookChapter.count({
    where: {
      bookId,
      level: 3,
      audioUrl: { not: '' }
    }
  });
  
  console.log(`书籍总数: ${beforeBooks}`);
  console.log(`AudioRecord记录: ${beforeAudioRecords}`);
  console.log(`已有音频的小节: ${beforeSubsectionsWithAudio}\n`);
  
  // 步骤2：调用批量生成音频API
  console.log('📤 步骤2：调用批量生成音频API\n');
  
  try {
    const response = await fetch(`http://localhost:3000/api/book-generator/langgraph/books/${bookId}/audio`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ voiceId: 'cherry' }),
    });
    
    const data = await response.json();
    
    console.log('API响应：');
    console.log(`  状态码: ${response.status}`);
    console.log(`  code: ${data.code}`);
    console.log(`  message: ${data.message}`);
    console.log(`  totalSubsections: ${data.data?.totalSubsections}\n`);
    
    if (data.code !== 0) {
      console.log('❌ API调用失败，测试终止');
      await prisma.$disconnect();
      return;
    }
    
    console.log('✅ API调用成功！\n');
  } catch (error) {
    console.log('❌ API调用异常:', error.message);
    await prisma.$disconnect();
    return;
  }
  
  // 步骤3：等待30秒让音频生成
  console.log('⏳ 步骤3：等待音频生成（30秒）...\n');
  await new Promise(resolve => setTimeout(resolve, 30000));
  
  // 步骤4：检查生成结果
  console.log('📊 步骤4：检查生成结果\n');
  
  const afterBooks = await prisma.book.count();
  const afterAudioRecords = await prisma.audioRecord.count({
    where: { userId: 1 }
  });
  const afterSubsectionsWithAudio = await prisma.bookChapter.count({
    where: {
      bookId,
      level: 3,
      audioUrl: { not: '' }
    }
  });
  
  console.log('对比结果：');
  console.log(`  书籍总数: ${beforeBooks} → ${afterBooks} ${afterBooks === beforeBooks ? '✅' : '❌ 增加了！'}`);
  console.log(`  AudioRecord: ${beforeAudioRecords} → ${afterAudioRecords} ${afterAudioRecords > beforeAudioRecords ? '✅ 增加了' : '⚠️ 未增加'}`);
  console.log(`  有音频的小节: ${beforeSubsectionsWithAudio} → ${afterSubsectionsWithAudio} ${afterSubsectionsWithAudio > beforeSubsectionsWithAudio ? '✅ 增加了' : '⚠️ 未增加'}\n`);
  
  // 步骤5：验证音频质量
  console.log('📝 步骤5：验证音频质量\n');
  
  const completedAudios = await prisma.audioRecord.findMany({
    where: {
      userId: 1,
      status: 'completed'
    },
    orderBy: { createdAt: 'desc' },
    take: 3,
    select: {
      id: true,
      title: true,
      status: true,
      audioUrl: true,
      audioDuration: true,
      wordCount: true,
      createdAt: true,
    }
  });
  
  if (completedAudios.length > 0) {
    console.log(`最近3个完成的音频：\n`);
    completedAudios.forEach((audio, index) => {
      console.log(`${index + 1}. ${audio.title}`);
      console.log(`   状态: ${audio.status}`);
      console.log(`   字数: ${audio.wordCount}字`);
      console.log(`   时长: ${audio.audioDuration}秒`);
      console.log(`   URL: ${audio.audioUrl || '无'}`);
      console.log(`   时间: ${audio.createdAt}\n`);
    });
  } else {
    console.log('⚠️ 还没有完成的音频，可能需要更长时间\n');
  }
  
  // 步骤6：检查是否创建了错误的书籍
  console.log('🔍 步骤6：检查是否创建了错误的"我的音频"书籍\n');
  
  const myAudioBooks = await prisma.book.count({
    where: { title: '我的音频' }
  });
  
  if (myAudioBooks === 0) {
    console.log('✅ 没有创建错误的"我的音频"书籍！\n');
  } else {
    console.log(`❌ 创建了${myAudioBooks}本"我的音频"书籍！\n`);
  }
  
  // 最终总结
  console.log('=' .repeat(60));
  console.log('\n📋 测试总结：\n');
  
  const allPassed = 
    afterBooks === beforeBooks && // 书籍数量没增加
    afterSubsectionsWithAudio > beforeSubsectionsWithAudio && // 音频小节增加了
    myAudioBooks === 0; // 没有错误的书籍
  
  if (allPassed) {
    console.log('✅ 所有测试通过！音频生成功能正常！\n');
  } else {
    console.log('❌ 部分测试未通过，请检查上面的详细结果\n');
  }
  
  await prisma.$disconnect();
}

testFullAudioGeneration().catch(console.error);
