class AudioAnalysis
  def initialize(video)
    @video = video
  end

  # Use the custom hash to generate JSON format
  def as_json(*)
    to_hash
  end

  def to_hash
    {
      edl_bucket_name: aws_bucket_name,
      edl_object_name: video.audio_only_edl_file.key,
      acquired_audio: acquired_audio_list,
      original_music: original_music_list,
    }
  end

  def results
    response.results
  end

  private

  attr_reader :video

  def aws_bucket_name
    ENV["AWS_BUCKET"]
  end

  def acquired_audio_list
    video.project.acquired_media_releases.flat_map do |acquired_media_release|
      acquired_media_release.file_infos.audio.map do |file_info|
        { id: file_info.id, filename: file_info.filename }
      end
    end
  end

  def original_music_list
    video.project.music_releases.flat_map do |music_release|
      music_release.file_infos.map do |file_info|
        { id: file_info.id, filename: file_info.filename, composers: music_release.composer_info, publishers: music_release.publisher_info }
      end
    end
  end

  def analysis_uid
    video.audio_analysis_uid
  end

  def fps
    edl_event_gateway.fps
  end

  def edl_offset_seconds
    edl_event_gateway.edl_offset_seconds
  end

  def edl_event_gateway
    # TODO: Eventually cache this on the video itself to avoid an extra API call, but for now keep it simple
    @edl_event_gateway ||= begin
                             files_for_request = AudioFilesForRequest.new(video, video.edl_timecode_start)
                             EdlEventGateway.new(files_for_request, "00:00:00:00", "00:00:00:00")
                           end
  end

  def response
    @response ||= BrayniacAI::AudioRecognition.find(analysis_uid, 
                                                    params: { fps: fps, edl_offset_seconds: edl_offset_seconds })
  end
end
