const path = require('path');
const fs = require('fs');
const { dbService } = require('./database/dbService');
const bookInfoService = require('./database/bookInfoService');
const uuid = require('uuid');
const ffmpeg = require('fluent-ffmpeg');

// 添加音频处理相关的IPC处理程序
const setupAudioProcessingHandlers = (ipcMain) => {
  // 获取音频时长
  ipcMain.handle('get-audio-duration', async (event, { audioPath }) => {
    try {
      const duration = await getAudioDuration(audioPath);
      return { success: true, duration };
    } catch (error) {
      console.error('获取音频时长失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 处理项目音频
  ipcMain.handle('process-project-audio', async (event, { projectId, audioPath, segments, outputDir }) => {
    try {
      // 确保输出目录存在
      const projectDir = path.join(outputDir, `project_${projectId}`);
      ensureDirectoryExists(projectDir);
      
      // 获取音频总时长
      const audioDuration = await getAudioDuration(audioPath);
      console.log(`音频总时长: ${audioDuration}秒`);
      
      // 按照字幕时间切割音频
      const results = [];
      
      for (const segment of segments) {
        // 解析开始和结束时间
        const startSeconds = timeToSeconds(segment.start_time);
        const endSeconds = timeToSeconds(segment.end_time);
        const segmentDuration = endSeconds - startSeconds;
        
        // 输出文件路径
        const outputFileName = `segment_${segment.id}_${segment.segment_id}.mp3`;
        const outputFilePath = path.join(projectDir, outputFileName);
        
        console.log(`处理片段 ${segment.id}: ${startSeconds}s - ${endSeconds}s (${segmentDuration}s)`);
        
        try {
          // 切割音频
          await cutAudioSegment(audioPath, outputFilePath, startSeconds, segmentDuration);
          
          // 添加到结果
          results.push({
            segmentId: segment.id,
            originalStartTime: segment.start_time,
            originalEndTime: segment.end_time,
            outputPath: outputFilePath,
            relativePath: path.join(`project_${projectId}`, outputFileName)
          });
          
        } catch (error) {
          console.error(`切割片段 ${segment.id} 失败:`, error);
        }
      }
      
      return {
        success: true,
        totalSegments: segments.length,
        processedSegments: results.length,
        segments: results
      };
    } catch (error) {
      console.error('处理项目音频失败:', error);
      return { success: false, error: error.message };
    }
  });
};

// 确保目录存在
const ensureDirectoryExists = (directory) => {
  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory, { recursive: true });
    console.log(`创建目录: ${directory}`);
  }
};

// 获取音频时长（秒）
const getAudioDuration = (audioPath) => {
  return new Promise((resolve, reject) => {
    ffmpeg.ffprobe(audioPath, (err, metadata) => {
      if (err) {
        return reject(err);
      }
      resolve(metadata.format.duration);
    });
  });
};

// 转换时间格式为秒
const timeToSeconds = (timeString) => {
  // 处理SRT格式: 00:00:12,345
  const normalizedTime = timeString.replace(',', '.');
  const [hours, minutes, seconds] = normalizedTime.split(':').map(parseFloat);
  return hours * 3600 + minutes * 60 + seconds;
};

// 切割音频片段
const cutAudioSegment = (inputFile, outputFile, startTime, duration) => {
  return new Promise((resolve, reject) => {
    ffmpeg(inputFile)
      .setStartTime(startTime)
      .setDuration(duration)
      .output(outputFile)
      .on('end', () => {
        console.log(`音频片段已保存: ${outputFile}`);
        resolve();
      })
      .on('error', (err) => {
        console.error('音频处理错误:', err);
        reject(err);
      })
      .run();
  });
};

module.exports = {
  setupAudioProcessingHandlers,
}; 