export class AudioRecorder {
  private mediaRecorder: MediaRecorder | null = null;
  private stream: MediaStream | null = null;
  private audioChunks: Blob[] = [];
  private isRecording = false;

  constructor(
    private onDataAvailable?: (audioBlob: Blob) => void,
    private onError?: (error: Error) => void
  ) {}

  async startRecording(): Promise<void> {
    try {
      // 请求麦克风权限
      this.stream = await navigator.mediaDevices.getUserMedia({
        audio: {
          sampleRate: 16000,
          channelCount: 1,
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true
        }
      });

      // 创建MediaRecorder实例
      const options: MediaRecorderOptions = {
        mimeType: 'audio/webm;codecs=opus'
      };

      // 检查浏览器支持的格式
      if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        options.mimeType = 'audio/webm';
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
          options.mimeType = 'audio/mp4';
          if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            options.mimeType = '';
          }
        }
      }

      this.mediaRecorder = new MediaRecorder(this.stream, options);
      this.audioChunks = [];

      // 设置事件监听器
      this.mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          this.audioChunks.push(event.data);
        }
      };

      this.mediaRecorder.onstop = () => {
        const audioBlob = new Blob(this.audioChunks, { 
          type: this.mediaRecorder?.mimeType || 'audio/webm' 
        });
        
        if (this.onDataAvailable) {
          this.onDataAvailable(audioBlob);
        }
        
        this.cleanup();
      };

      this.mediaRecorder.onerror = (event) => {
        const error = new Error(`录音错误: ${event.error || '未知错误'}`);
        if (this.onError) {
          this.onError(error);
        }
        this.cleanup();
      };

      // 开始录音
      this.mediaRecorder.start();
      this.isRecording = true;
      
      console.log('开始录音...');
    } catch (error) {
      const recordingError = new Error(`无法访问麦克风: ${error.message}`);
      if (this.onError) {
        this.onError(recordingError);
      }
      throw recordingError;
    }
  }

  stopRecording(): void {
    if (this.mediaRecorder && this.isRecording) {
      this.mediaRecorder.stop();
      this.isRecording = false;
      console.log('停止录音...');
    }
  }

  getRecordingState(): boolean {
    return this.isRecording;
  }

  private cleanup(): void {
    if (this.stream) {
      this.stream.getTracks().forEach(track => track.stop());
      this.stream = null;
    }
    
    this.mediaRecorder = null;
    this.isRecording = false;
  }

  // 将音频Blob转换为base64
  static async blobToBase64(blob: Blob): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const result = reader.result as string;
        // 移除data:audio/...;base64,前缀
        const base64 = result.split(',')[1];
        resolve(base64);
      };
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  }

  // 检查浏览器是否支持录音
  static isSupported(): boolean {
    return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia && window.MediaRecorder);
  }
}