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

async function testNewAudioGeneration() {
  console.log('\n🎵 测试新生成的音频路径\n');
  console.log('=' .repeat(60));
  
  const bookId = 5;
  
  // 找到一个小节
  const subsection = await prisma.bookChapter.findFirst({
    where: {
      bookId,
      level: 3
    },
    select: {
      id: true,
      title: true,
      content: true,
      audioUrl: true,
    }
  });
  
  if (!subsection) {
    console.log('❌ 找不到小节\n');
    await prisma.$disconnect();
    return;
  }
  
  console.log(`测试小节: ${subsection.title}`);
  console.log(`ID: ${subsection.id}`);
  console.log(`当前audioUrl: ${subsection.audioUrl || '无'}\n`);
  
  // 调用API重新生成音频（使用批量生成）
  console.log('📤 调用批量音频生成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}\n`);
    
    if (data.code !== 0) {
      console.log('❌ API调用失败\n');
      await prisma.$disconnect();
      return;
    }
    
    console.log('✅ API调用成功，等待15秒让音频生成完成...\n');
    await new Promise(resolve => setTimeout(resolve, 15000));
    
    // 检查新生成的音频URL
    console.log('📊 检查新生成的音频URL:\n');
    
    const updatedChapter = await prisma.bookChapter.findUnique({
      where: { id: subsection.id },
      select: {
        id: true,
        title: true,
        audioUrl: true,
        audioDuration: true,
      }
    });
    
    console.log(`章节: ${updatedChapter.title}`);
    console.log(`audioUrl: ${updatedChapter.audioUrl || '无'}`);
    console.log(`audioDuration: ${updatedChapter.audioDuration || 0}秒\n`);
    
    // 检查文件
    const fs = require('fs');
    const path = require('path');
    
    const uuid = updatedChapter.audioUrl.match(/\/uploads\/([^\/]+)\//)?.[1];
    if (uuid) {
      const filePath = path.join(__dirname, 'uploads', uuid, 'output.mp3');
      const segmentPath = path.join(__dirname, 'uploads', uuid, 'segment_0.mp3');
      
      console.log('📁 检查文件:\n');
      console.log(`output.mp3: ${fs.existsSync(filePath) ? '✅ 存在' : '❌ 不存在'}`);
      console.log(`segment_0.mp3: ${fs.existsSync(segmentPath) ? '✅ 存在' : '❌ 不存在'}\n`);
      
      if (fs.existsSync(filePath)) {
        const stats = fs.statSync(filePath);
        console.log(`output.mp3 大小: ${(stats.size / 1024).toFixed(2)} KB\n`);
      }
      
      console.log('=' .repeat(60));
      console.log('\n📋 测试结论:\n');
      
      if (updatedChapter.audioUrl?.includes('output.mp3')) {
        console.log('✅ 音频URL使用output.mp3，路径正确！\n');
      } else if (updatedChapter.audioUrl?.includes('segment_0.mp3')) {
        console.log('❌ 音频URL仍使用segment_0.mp3，需要修复\n');
      } else {
        console.log('⚠️ 未知情况\n');
      }
    }
    
  } catch (error) {
    console.log('❌ 测试失败:', error.message);
    console.log(error.stack);
  }
  
  await prisma.$disconnect();
}

testNewAudioGeneration().catch(console.error);
