#! /usr/bin/env Rscript

doc <- "Read an SUNSET recipe template and write a new recipe with the 
specified start date, data stream (hcst or fcst) and Autosubmit expid,
in order to easily use SUNSET for operational analysis and verification.

Usage:
    recipe_maker.R <recipe_template> [--sd=<start_date>] [--horizon=<horizon>] [--stream=<stream>] [--expid=<expid>]

Options:
    -h --help  Show usage.
    --sd=<start_date>  Start date.
    --horizon=<horizon>  Forecast horizon (seasonal, subseasonal or decadal).
    --stream=<stream>  Stream (hcst or fcst). [default: fcst]
    --expid=<expid>  Autosubmit experiment ID.
    
Arguments:
    recipe_template  path to the recipe template."
    
library(docopt)
library(tools)
## TODO: Maybe we don't need to load everything
suppressMessages(source("tools/libs.R"))
options(error=function()traceback(2))

arguments <- docopt(doc = doc)
start_date <- arguments$sd

recipe <- read_yaml(arguments$recipe_template)

## TODO: Add exception for subseasonal case
if (arguments$horizon %in% c("seasonal", "decadal")) {
  recipe$Analysis$Time$sdate <- substring(start_date, 5, 8)
  if (arguments$stream == "fcst") {
    recipe$Analysis$Time$fcst_year <- substring(start_date, 1, 4)
  }
} else if (arguments$horizon == "subseasonal") {
  recipe$Analysis$Time$sdate <- start_date
  recipe$Analysis$Time$fcst_year <- substring(start_date, 1, 4)
}

if (recipe$Run$autosubmit) {
  recipe$Run$auto_conf$expid <- arguments$expid
}

recipe_name <- paste0(basename(file_path_sans_ext(arguments$recipe_template)),
                      "_oper_", start_date)
recipe_file <- paste0(dirname(arguments$recipe_template), "/", recipe_name, ".yml")

write_yaml(recipe, file = recipe_file)

cat(paste(recipe_file, recipe$Run$auto_conf$script))
