class Gladia
  API_URL = "https://api.gladia.io/v2/pre-recorded"

  def self.retrieve(id:, respondent:, translated: false)
    response = HTTP.headers(
      "Content-Type": "application/json",
      "x-gladia-key": Rails.application.credentials.gladia[:key]
    ).get(
      "#{API_URL}/#{id}"
    )
    data = JSON.parse(response.body.to_s)

    if translated
      # case where audio with no dialogues returns an empty transcription, do nothing
      return if data.dig("result", "translation", "is_empty") == true

      transcript = data["result"]["translation"]["results"].first["utterances"]
    else
      # case where audio with no dialogues returns an empty transcription, do nothing
      return if data.dig("result", "transcription", "is_empty") == true

      transcript = data["result"]["transcription"]["utterances"]
    end

    transcript.each do |row|
      row["speaker"] = "SPEAKER_#{row['speaker']}"
    end

    # TODO: handle this rare case
    return if respondent.whisper_transcript.present?

    WhisperTranscript.create!(respondent_id: respondent.id, verbose_json: transcript)
  end

  def self.transcribe(respondent, language: "en", translation: true)
    request_body = {
      audio_url: respondent.audio_file.url(:original, timestamp: false),
      translation:,
      translation_config: { target_languages: ["en"] },
      diarization: true,
      diarization_config: respondent.speaker_count ? { number_of_speakers: respondent.speaker_count } : nil,
      detect_language: true,
      enable_code_switching: false,
      custom_vocabulary: respondent.proper_nouns.empty? || respondent.proper_nouns == [""] ? false : true,
      custom_vocabulary_config: {
        vocabulary: respondent.proper_nouns
      }
    }.compact
    response = HTTP.headers(
      "Content-Type": "application/json",
      "x-gladia-key": Rails.application.credentials.gladia[:key]
    ).post(
      API_URL,
      json: request_body
    )
    JSON.parse(response.body.to_s)
  end
end
