# Transcriber Model
class Transcriber
  SCRIPT_PATH = "/home/fareesh/scripts/sprint"

  def self.process_video(video_path, respondent_id)
    require "shellwords"

    audio_path = Transcriber.convert_video(video_path)
    return unless audio_path

    Rails.logger.debug("Transcribing #{audio_path}")

    result = `#{SCRIPT_PATH}/transcribe.sh #{Shellwords.escape(audio_path)}`
    Rails.logger.debug("Transcription complete")

    require "json"
    json = JSON.parse(result)
    WhisperTranscript.create!(respondent_id:, text: json["text"])
  end

  def self.convert_video(video_path)
    require "shellwords"
    require "open3"
    require "pathname"

    # Check if the video file exists
    unless File.exist?(video_path)
      Rails.logger.debug("Video file not found: #{video_path}")
      return nil
    end

    # Set the output path to the same as input, but with .mp3 extension
    output_path = Pathname.new(video_path).sub_ext(".mp3").to_s

    # Escape paths and filenames
    video_path = Shellwords.escape(video_path)
    output_path = Shellwords.escape(output_path)

    # Run FFmpeg command to convert video to MP3
    cmd = "ffmpeg -y -i #{video_path} -vn -acodec libmp3lame #{output_path}"
    Rails.logger.debug("Executing #{cmd}")
    Open3.popen3(cmd) do |_stdin, _stdout, stderr, _wait_thr|
      error_message = stderr.read
      if error_message.empty?
        Rails.logger.debug("Successfully converted #{video_path} to #{output_path}")
      else
        Rails.logger.debug("Failed to convert #{video_path} to #{output_path}:")
        Rails.logger.fatal(error_message)
      end
    end
    output_path
  end
end
