source('tools/libs.R')
source('modules/Scorecards/Scorecards.R')

args = commandArgs(trailingOnly = TRUE)
recipe_file <- args[1]
output_dir <- args[2]

## for testing

recipe_file <- '/esarchive/scratch/nmilders/multimodel/recipe_multimodel_seasonal_nadia_test.yml'
output_dir <- '/esarchive/scratch/nmilders/scorecards_data/multimodel/test/recipe_multimodel_seasonal_nadia_test_20240223114714'


## TODO: Replace with function
# Read recipe and set outdir
recipe <- read_yaml(recipe_file)
recipe$Run$output_dir <- output_dir

## Loop over variables
datasets <- recipe$Analysis$Datasets
## TODO: Improve dependency system?
for (variable in 1:length(recipe$Analysis$Variables)) {
      scorecard_recipe <- recipe 
  
      scorecard_recipe$Analysis$Datasets$System <- 
        as.vector(unlist(recipe$Analysis$Datasets$System))
      
      ## Include multimodel in systems 
      if(isTRUE(scorecard_recipe$Analysis$Datasets$Multimodel$execute) ||
         scorecard_recipe$Analysis$Datasets$Multimodel$execute == 'both' ||
         scorecard_recipe$Analysis$Datasets$Multimodel$execute == 'yes'){
        scorecard_recipe$Analysis$Datasets$System <- 
          c(scorecard_recipe$Analysis$Datasets$System, 'Multimodel')
      }

      scorecard_recipe$Analysis$Datasets$Reference <- 
        as.vector(unlist(recipe$Analysis$Datasets$Reference))
      scorecard_recipe$Analysis$Variables <-
        recipe$Analysis$Variables[[variable]]
      # Plot Scorecards
      Scorecards(scorecard_recipe)
}
print("##### SCORECARDS SAVED TO THE OUTPUT DIRECTORY #####")
