source("modules/Loading/Loading.R")
source("modules/Units/Units.R")
source("modules/Preprocessing/Preprocessing.R")
source("modules/Skill/Skill.R")
source("modules/Saving/Saving.R")
source("modules/Visualization/Visualization.R")
source("build_compute_workflow_crossval.R")

# recipe_file <- "/gpfs/projects/bsc32/bsc032762/git/vic-personal-code/auto-s2s-tests/cross-validation-global/recipe_scorecards_example.yml"
# recipe_file <- "/home/Earth/vagudets/oldhome/git/victoria-personal-code/auto-s2s-tests/cross-validation-global/recipe_scorecards_example.yml"
# recipe <- prepare_outputs(recipe_file)

args <- commandArgs(trailingOnly = TRUE)
recipe_file <- args[1]
recipe <- read_atomic_recipe(recipe_file)

#### LOAD MODULES ####

## TODOs:
## 1. Statistics -> DONE
## 2. Do not return hcst, fcst and obs -> DONE-ish (Should be generalized)
## 3. Recipe checks -> DONE-ish (should be generalized)
## 4. Test without orography correction (full workflow) -> DONE 
## 5. Fix everything to make sure retrieve = TRUE works well (full workflow)
## 6. orography correction -> DONE 
## 7. enssprerr and SprErr do not have the same name: problem? Check Nadia's branch -> DONE-ish (needs merging)
## 8. Workflow requirements (check multimodel case)

# Load datasets
data <- Loading(recipe, retrieve = F)

# Run workflow with compute
result <- run_compute_workflow(recipe, data)

Visualization(recipe = recipe, data = result$data,
              skill_metrics = result$skill, significance = TRUE,
              output_conf = NULL)

if (recipe$Analysis$Workflow$Scorecards$metric_aggregation == 'score') {
  Visualization(recipe = recipe, data = result$data,
                skill_metrics = result$statistics, significance = F,
                output_conf = NULL)
} else {
  statistics <- NULL
}

## Add logo to plots
source("tools/add_logo.R")
add_logo(recipe, "rsz_rsz_bsc_logo.png")

if (recipe$Analysis$Dataset$System$name == 'UK-MetOffice-Glosea601'
    & recipe$Analysis$Time$sdate == '0101'
    & recipe$Analysis$Time$hcst_start == '1994'){
  recipe$Analysis$Time$hcst_start <- '1993'
}

## Scorecards spatial aggregation of metrics
if (recipe$Analysis$Workflow$Scorecards$execute == TRUE) {
  source("modules/Scorecards/Scorecards_calculations.R")
  Scorecards_calculations(recipe = recipe, data = result$data,
                          skill_metrics = result$skill,
                          statistics = result$statistics)
}

