source("modules/Loading/Loading.R")
source("modules/Saving/Saving.R")
source("modules/Units/Units.R")
source("modules/Visualization/Visualization.R")
source("modules/Aggregation/Aggregation.R")
#args = commandArgs(trailingOnly = TRUE)
#recipe_file <- args[1]
recipe_file <- "/esarchive/scratch/ptrascas/R/dev-test_bigpredidata/sunset/sunset/recipes/recipe_bigpredidata_oper_test_tas.yml"
#recipe_file <- "recipe_subseasonal_ecvs.yml"
#recipe_file <- "recipe_prlr_cal_subseas.yml"

recipe <- read_atomic_recipe(recipe_file)
#recipe <- prepare_outputs(recipe_file)

# Load datasets
data <- Loading(recipe)
data <- Units(recipe, data)
data_summary(data$hcst, recipe)
data_summary(data$obs, recipe)
if (!is.null(data$fcst)) {
  data_summary(data$fcst, recipe)
}


source("modules/Crossval/Crossval_Calibration.R")
res <- Crossval_Calibration(recipe = recipe, data = data)

source("modules/Crossval/Crossval_metrics.R")
skill_metrics <- Crossval_metrics(recipe = recipe, data_crossval = res,
                                fair = FALSE, nmemb = NULL, nmemb_ref = NULL) 

if (!is.null(data$fcst)) {
  # Required to plot a forecast:
  data$fcst <- res$fcst
  tmp_probs <- list(probs_fcst = res$probs$fcst[[1]])
  nlats <- as.numeric(dim(data$hcst$data)['latitude'])
  nlons <- as.numeric(dim(data$hcst$data)['longitude'])
  ntimes <- as.numeric(dim(data$hcst$data)['time'])

  #   TODO: consider more than terciles
  dim(tmp_probs$probs_fcst) <- c(bin = 3, syear = 1, var = 1, time = ntimes,
  			       latitude = nlats, longitude = nlons)


  Visualization(recipe = recipe, data = data, skill_metrics = skill_metrics,
		significance = TRUE, probabilities = tmp_probs,
		logo = NULL)
                #logo = "tools/BSC_logo_95.jpg")
} else {
    Visualization(recipe = recipe, data = data, skill_metrics = skill_metrics, 
		  significance = TRUE, log = "tools/BSC_logo_95.jpg")
}

saveRDS(object = list(product = res,
		      metrics = skill_metrics, 
		      fcst_probs = tmp_probs),
	file = paste0(recipe$Run$output_dir, "/outputs/",
		      recipe$Analysis$Datasets$System$name, "_",
		      recipe$Analysis$Variables$name, "_",
		      recipe$Analysis$Time$fcst_year, ".RDS"))
recipe$Run$output_dir

