## TODO: Separate by time aggregation

get_dir <- function(recipe, variable, agg = "global") {
  # This function builds the path for the output directory. The output
  # directories will be subdirectories within outdir, organized by variable,
  # startdate, and aggregation.

  ## TODO: Get aggregation from recipe
  ## TODO: Change variable name to s2dv_cube name
  # variable <- strsplit(recipe$Analysis$Variables$name, ", | |,")[[1]]
  outdir <- recipe$Run$output_dir
  system <- gsub('.','', recipe$Analysis$Datasets$System$name, fixed = T)
  reference <- gsub('.','', recipe$Analysis$Datasets$Reference$name, fixed = T)
  calib.method <- tolower(recipe$Analysis$Workflow$Calibration$method)

  if (tolower(recipe$Analysis$Output_format) == 'scorecards') {
    # Define output dir name accordint to Scorecards format
    dict <- read_yaml("conf/output_dictionaries/scorecards.yml")
    # system <- dict$System[[recipe$Analysis$Datasets$System$name]]$short_name
    dir <- paste0(outdir, system, "/", reference, "/", calib.method, "/", variable, "/")
  } else {
    # Default generic output format based on FOCUS
    # Get startdate or hindcast period
    if (!is.null(recipe$Analysis$Time$fcst_year)) {
      if (tolower(recipe$Analysis$Horizon) == 'decadal') {
        ## PROBLEM: decadal doesn't have sdate
        fcst.sdate <- paste0(recipe$Analysis$Time$fcst_year, collapse = '_')
      } else {
        fcst.sdate <- paste0(recipe$Analysis$Time$fcst_year,
                             recipe$Analysis$Time$sdate)
      }
    } else {
      if (tolower(recipe$Analysis$Horizon) == 'decadal') {
        ## PROBLEM: decadal doesn't have sdate
        fcst.sdate <- paste0("hcst-", paste(recipe$Analysis$Time$hcst_start,
                                            recipe$Analysis$Time$hcst_end,
                                            sep = '_'))
      } else {
        fcst.sdate <- paste0("hcst-", recipe$Analysis$Time$sdate)
      }
    }
    ## TODO: Remove calibration method from output directory?
    store.freq <- recipe$Analysis$Variables$freq
    ## TODO: Change "_country"
    if (!is.null(recipe$Analysis$Region$name)) {
      outdir <- paste0(outdir, "/", recipe$Analysis$Region$name)
    }
    switch(tolower(agg),
         "country" = {dir <- paste0(outdir, "/", system, "/", calib.method,
                                    "-", store.freq, "/", variable, 
                                    "_country/", fcst.sdate, "/")},
         "global" = {dir <- paste0(outdir, "/", system, "/", calib.method,
                                   "-", store.freq, "/", variable, "/",
                                   fcst.sdate, "/")})
  }

  return(dir)
}
