import fs from 'fs';
import path from 'path';
import { VoiceParams } from '../../types';
import { ITtsProvider } from './provider.interface';
import { logAiCall } from '../../services/ai-call-logger';

// 模拟 TTS Provider（不调任何外部API，直接返回占位音频）
export class MockTtsProvider implements ITtsProvider {
  readonly name = 'mock-tts';
  readonly vendor = 'mock';
  readonly mode = 'mock' as const;
  readonly maxTextLength = 10000;
  readonly concurrency = 2;
  readonly modelId = 'mock-tts';
  readonly ttsApiPath = '';

  async synthesize(
    text: string,
    voiceId: string,
    params: VoiceParams,
    outputPath: string
  ): Promise<string> {
    const startTime = Date.now();
    // 随机 40% 失败率，用于测试 TtsQueue 重试机制
    const shouldFail = Math.random() < 0.4;

    try {
      if (shouldFail) {
        throw new Error('Mock 模拟失败：测试重试机制');
      }

      const dir = path.dirname(outputPath);
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }

      const minimalMp3 = Buffer.from([
        0xff, 0xfb, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
      ]);
      fs.writeFileSync(outputPath, minimalMp3);

      logAiCall({
        callType: 'tts_mock',
        provider: 'mock',
        model: 'mock-tts',
        textLen: text.length,
        duration: Date.now() - startTime,
        success: true,
      });

      return outputPath;
    } catch (error: any) {
      logAiCall({
        callType: 'tts_mock',
        provider: 'mock',
        model: 'mock-tts',
        textLen: text.length,
        duration: Date.now() - startTime,
        success: false,
        errorMsg: error.message,
      });
      throw error;
    }
  }
}