#!/usr/bin/env bash

currentPerformanceYear=$(($1))
maxPerformanceYear=2027

Red='\033[0;31m'
Green='\033[0;32m'
bold=$(tput bold)

# checks the exit code of the last command and exits if not successful code 0.
function exitOnFailure () {
  if (( $? != 0 )); then
    echo -e "${Red}\n${bold}Update failed."
    exit
  fi
}

# This script is not made to work for years prior to 2023.
if (( $currentPerformanceYear >= 2023 )) && (( $currentPerformanceYear <= $maxPerformanceYear )); then

  echo -e "Compiling Typescript..."
  tsc -p .


  # Convert all CSV benchmark files to JSON.
  for FILE in staging/$currentPerformanceYear/benchmarks/*; do
    re='^(.+\/)*(.+)\.(.+)$'
    if [[ $FILE =~ $re ]]; then
      echo -e "Converting $FILE.csv to JSON..."
      node dist/scripts/benchmarks/csv-json-converter.js \
        staging/$currentPerformanceYear/benchmarks/${BASH_REMATCH[2]}.csv $currentPerformanceYear ${BASH_REMATCH[2]}
      
      # validate the JSON files before combining
      node dist/scripts/benchmarks/validation.business.js \
        ${BASH_REMATCH[2]}.json $currentPerformanceYear
      
      exitOnFailure
    fi
  done
  
  
  # Convert all CSV benchmark util files to JSON.
  for FILE in util/benchmarks/$currentPerformanceYear/*; do
    re='^(.+\/)*(.+)\.(.+)$'
    if [[ $FILE =~ $re ]]; then
      echo -e "Converting $FILE.csv to JSON..."
      node dist/scripts/benchmarks/update-cost-national-averages.js \
        util/benchmarks/$currentPerformanceYear/${BASH_REMATCH[2]}.csv $currentPerformanceYear ${BASH_REMATCH[2]}
      
      # validate the JSON files
      echo -e "Validating new $FILE.json"
      node dist/scripts/validate-data.js ${BASH_REMATCH[2]} $currentPerformanceYear benchmarks/$currentPerformanceYear/${BASH_REMATCH[2]}.json benchmarks
      
      exitOnFailure
    fi
  done
  
  
  # merge all benchmark files into one.
  echo -e "Merging individual JSON files..."
  node dist/scripts/benchmarks/merge-benchmark-files.js \
    staging/$currentPerformanceYear/benchmarks/json/ $currentPerformanceYear


  # Validate benchmarks.
  echo -e "Validating new benchmarks JSON."
  node dist/scripts/validate-data.js benchmarks $currentPerformanceYear benchmarks/$currentPerformanceYear.json
  exitOnFailure
  
  echo -e "${Green}\n${bold}Update complete."
  exit

else
  echo -e "${Red}${bold}Performance year ${currentPerformanceYear} not valid."
fi
