#!/usr/bin/env ruby
# frozen_string_literal: true

$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', 'app'))

require 'aws-sdk-s3'
require 'indicina'
require 'json'

Aws.config.update profile: 'cpe-benchmarking', region: 'us-east-1'
s3_archive = Aws::S3::Resource.new.bucket('cpe-benchmarking-archive-useast1-c75217b4b9281ba043961e533e601e')

def process_json(test_id, s3_obj)
  puts 'Treating as json test results.'.indent

  test = Indicina.tests.by_pk(test_id)
  if test&.parse_complete
    puts 'Test data already indexed!'.indent
    return
  end

  puts 'Downloading from s3...'.indent
  results = JSON.parse(s3_obj.get.body.read)

  if results['data']['location'].nil?
    puts 'Test data is missing its location.  Skipping.'.indent
    return
  end

  if test.nil?
    puts 'Indexing initial test data...'.indent
    Indicina.tests.store(s3_obj, results['data'])
    test = Indicina.tests.by_pk(test_id)
  end

  puts 'Indexing run data...'.indent
  median_run = results['data']['median'].is_a?(Hash) ? results['data']['median']['firstView']['run'] : -1
  results['data']['runs'].each_value do |data|
    if data['firstView']['loadTime'].nil?
      puts "Skipping run #{data['firstView']['run']} as it's missing load_time.".indent(2)
      next
    end

    Indicina.runs.store(test, data['firstView'], median_run == data['firstView']['run'])
  end

  run_count = Indicina.runs.by_test(test).count
  puts "Stored #{run_count} runs for test #{test_id}.".indent(2)
  puts "Marking #{test_id} as completely parsed.".indent

  Indicina.tests.update test_id, parse_complete: true
end

def process_mp4(test_id, s3_obj)
  puts 'Treating as test video output.'.indent

  test = Indicina.tests.by_pk(test_id)

  if test&.has_video
    puts 'Video data already indexed!'.indent
    return
  end

  puts 'Indexing video data.'.indent
  Indicina.tests.create id: test_id if test.nil?
  Indicina.tests.update test_id, has_video: true, video_url: "#{Indicina::CDN_DOMAIN}#{s3_obj.key}"
  puts 'Complete!'.indent(2)
end

s3_archive.objects.each do |s3_obj|
  test_id, file_type = s3_obj.key.split('/')[-1].split('.')
  puts "Processing #{test_id}.#{file_type}..."

  case file_type
    when 'error'
      puts 'Skipping .error file.'.indent
    when 'mp4'
      process_mp4(test_id, s3_obj)
    when 'json'
      process_json(test_id, s3_obj)
  end
end
