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

async function testAudioUrl() {
  console.log('\n📊 测试音频URL可访问性：\n');
  
  const chapter = await prisma.bookChapter.findUnique({
    where: { id: 1214 }
  });
  
  if (!chapter || !chapter.audioUrl) {
    console.log('❌ 没有音频URL\n');
    await prisma.$disconnect();
    return;
  }
  
  console.log(`章节: ${chapter.title}`);
  console.log(`audioUrl: ${chapter.audioUrl}\n`);
  
  // 测试本地文件是否存在
  const fs = require('fs');
  const path = require('path');
  
  // audioUrl格式: /uploads/{uuid}/output.mp3
  const uuid = chapter.audioUrl.match(/\/uploads\/([^\/]+)\//)?.[1];
  if (uuid) {
    const filePath = path.join(__dirname, 'uploads', uuid, 'output.mp3');
    console.log(`文件路径: ${filePath}`);
    
    if (fs.existsSync(filePath)) {
      const stats = fs.statSync(filePath);
      console.log(`✅ 文件存在，大小: ${(stats.size / 1024).toFixed(2)} KB\n`);
    } else {
      console.log(`❌ 文件不存在\n`);
    }
  }
  
  // 测试API访问
  console.log('测试HTTP访问: http://localhost:3000' + chapter.audioUrl);
  
  const url = 'http://localhost:3000' + chapter.audioUrl;
  
  return new Promise((resolve) => {
    http.get(url, (res) => {
      console.log(`\nHTTP响应状态: ${res.statusCode}`);
      console.log(`Content-Type: ${res.headers['content-type']}`);
      console.log(`Content-Length: ${res.headers['content-length']}\n`);
      
      if (res.statusCode === 200) {
        console.log('✅ 音频URL可以通过HTTP访问\n');
      } else {
        console.log('❌ 音频URL无法通过HTTP访问\n');
      }
      
      resolve();
    }).on('error', (err) => {
      console.log(`❌ HTTP请求失败: ${err.message}\n`);
      resolve();
    });
  });
}

testAudioUrl().then(() => prisma.$disconnect()).catch(console.error);
