// ============================================
// GOOGLE CLOUD SPEECH-TO-TEXT INTEGRATION
// ============================================

class GoogleSpeechRecognition {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.isListening = false;
    this.mediaRecorder = null;
    this.audioChunks = [];
    this.stream = null;
    this.onResultCallback = null;
    this.onErrorCallback = null;
    this.recordingInterval = null;
    this.silenceTimeout = null;
  }

  // Start recording
  async start() {
    if (this.isListening) return;

    try {
      // Get microphone access
      this.stream = await navigator.mediaDevices.getUserMedia({ 
        audio: {
          channelCount: 1,
          sampleRate: 16000,
          echoCancellation: true,
          noiseSuppression: true
        }
      });

      // Create MediaRecorder
      this.mediaRecorder = new MediaRecorder(this.stream, {
        mimeType: 'audio/webm;codecs=opus'
      });

      this.audioChunks = [];

      this.mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          this.audioChunks.push(event.data);
        }
      };

      this.mediaRecorder.onstop = async () => {
        if (this.audioChunks.length > 0) {
          await this.processAudio();
        }
      };

      // Start recording
      this.mediaRecorder.start();
      this.isListening = true;

      // Auto-stop after 5 seconds and process
      this.recordingInterval = setTimeout(() => {
        if (this.isListening) {
          this.stopAndProcess();
        }
      }, 5000);

      console.log('Google Speech: Recording started');
      
    } catch (error) {
      console.error('Error starting recording:', error);
      if (this.onErrorCallback) {
        this.onErrorCallback(error);
      }
    }
  }

  // Stop recording and process
  stopAndProcess() {
    if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
      this.mediaRecorder.stop();
    }
    if (this.recordingInterval) {
      clearTimeout(this.recordingInterval);
    }
  }

  // Stop completely
  stop() {
    this.isListening = false;
    
    if (this.recordingInterval) {
      clearTimeout(this.recordingInterval);
      this.recordingInterval = null;
    }

    if (this.silenceTimeout) {
      clearTimeout(this.silenceTimeout);
      this.silenceTimeout = null;
    }

    if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
      this.mediaRecorder.stop();
    }

    if (this.stream) {
      this.stream.getTracks().forEach(track => track.stop());
      this.stream = null;
    }

    this.audioChunks = [];
    console.log('Google Speech: Stopped');
  }

  // Process audio with Google Cloud Speech-to-Text API
  async processAudio() {
    try {
      // Convert audio chunks to base64
      const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' });
      const base64Audio = await this.blobToBase64(audioBlob);

      console.log('Google Speech: Processing audio...');

      // Call Google Cloud Speech-to-Text API
      const response = await fetch(
        `https://speech.googleapis.com/v1/speech:recognize?key=${this.apiKey}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            config: {
              encoding: 'WEBM_OPUS',
              sampleRateHertz: 16000,
              languageCode: 'vi-VN',
              enableAutomaticPunctuation: true,
              model: 'default'
            },
            audio: {
              content: base64Audio.split(',')[1] // Remove data:audio/webm;base64, prefix
            }
          })
        }
      );

      const data = await response.json();

      if (data.results && data.results.length > 0) {
        const transcript = data.results[0].alternatives[0].transcript;
        console.log('Google Speech: Transcript:', transcript);
        
        if (this.onResultCallback) {
          this.onResultCallback(transcript);
        }

        // Auto-restart if still listening
        if (this.isListening) {
          this.audioChunks = [];
          setTimeout(() => {
            if (this.isListening) {
              this.start();
            }
          }, 500);
        }
      } else {
        console.log('Google Speech: No results');
        
        // Auto-restart even if no results
        if (this.isListening) {
          this.audioChunks = [];
          setTimeout(() => {
            if (this.isListening) {
              this.start();
            }
          }, 500);
        }
      }

    } catch (error) {
      console.error('Error processing audio:', error);
      if (this.onErrorCallback) {
        this.onErrorCallback(error);
      }

      // Auto-restart on error
      if (this.isListening) {
        this.audioChunks = [];
        setTimeout(() => {
          if (this.isListening) {
            this.start();
          }
        }, 1000);
      }
    }
  }

  // Convert Blob to Base64
  blobToBase64(blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  }

  // Set callbacks
  onResult(callback) {
    this.onResultCallback = callback;
  }

  onError(callback) {
    this.onErrorCallback = callback;
  }
}

// Export
if (typeof module !== 'undefined' && module.exports) {
  module.exports = GoogleSpeechRecognition;
}
