#' @title Directed metadata graph construction for SUNSET's Loading module
#' @description Generate provenance for a SUNSET workflow involving loading of climate 
#'              forecast, hindcast and observational data.
#' @param recipe Configuration file specifying parameters.
#' @param data s2dv_cube object generated by SUNSET's Loading.R function.
#' @details This function constructs provenance information for a SUNSET workflow, 
#'          specifically focusing on the loading module. It generates provenance for 
#'          climate forecast hindcast and observational data, including dataset subsets 
#'          and reggriding information. The function integrates other provenance generation 
#'          functions to create a comprehensive metadata graph.
#' @references SUNSET GitLab Repository: https://earth.bsc.es/gitlab/es/sunset/-/wikis/home
#'             This repository hosts SUNSET, a modular tool for subseasonal to seasonal to decadal forecast 
#'             verification workflows. It is structured modularly to allow skipping or reordering 
#'             workflow parts.
#' @references https://earth.bsc.es/gitlab/es/sunset/-/wikis/home GitLab repository for SUNSET, 
#'             a modular tool for climate forecast verification workflows.
#' @references This function is based on the semantics outlined in the ontology within the Metaclip 
#'             Framework (available at \url{http://www.metaclip.org/}).

source("provenance/R/prov_dataset.R")
source("provenance/R/prov_datasetsubset.R")
source("provenance/R/prov_regridding.R")
source("provenance/prov_Command.R")
source("provenance/R/prov_helpers.R")

library(igraph)

prov_Loading <- function(recipe, data) {
  #fcst definition (Dataset + Datasubset + Regridding)
  if (!is.null(data$fcst)) {
    graph_fcst <- prov_dataset(recipe, data, type = "fcst")
    graph_fcst <- prov_datasetsubset(recipe, data, graph_fcst)
    graph_fcst <- prov_regridding(recipe, data, graph_fcst)
  }
  #hcst definition (Dataset + Datasubset + Regridding)
  graph_hcst <- prov_dataset(recipe, data, type = "hcst")
  graph_hcst <- prov_datasetsubset(recipe, data, graph_hcst)
  graph_hcst <- prov_regridding(recipe, data, graph_hcst)

  #obs definition (Dataset + Datasubset + Regridding)
  graph_obs <- prov_dataset(recipe, data, type = "obs")
  graph_obs <- prov_datasetsubset(recipe, data, graph_obs)
  graph_obs <- prov_regridding(recipe, data, graph_obs)

  #Command Call and output definition
  if (!is.null(data$fcst)) {
    graph <- my_union_graph(graph_fcst$graph, graph_hcst$graph, graph_obs$graph)

    graph <- prov_Command(graph, package = "Loading",
                          version = "2.0.0",
                          fun = "modules/Loading/Loading.R",
                          arg.list =
                            list(
                                 "Recipe",
                                 "Data"),
                          origin.node.name =
                            list(
                                 graph_fcst$parentnodename,
                                 graph_hcst$parentnodename,
                                 graph_obs$parentnodename,
                                 "DatasetSubset_fcst",
                                 "DatasetSubset_hcst",
                                 "DatasetSubset_obs"))

    graph <- list("graph" = graph,
                  "parentnodename" =
                    list(
                         "parentnodename_fcst" = graph_fcst$parentnodename,
                         "parentnodename_hcst" = graph_hcst$parentnodename,
                         "parentnodename_obs" = graph_obs$parentnodename))
  } else {
    graph <- my_union_graph(graph_hcst$graph, graph_obs$graph)
    graph <- prov_Command(graph, package = "Loading",
                          version = "2.0.0",
                          fun = "modules/Loading/Loading.R",
                          arg.list =
                            list(
                                 "Recipe",
                                 "Data"),
                          origin.node.name =
                            list(
                                 graph_hcst$parentnodename,
                                 graph_obs$parentnodename,
                                 "DatasetSubset_hcst",
                                 "DatasetSubset_obs"))

    graph <- list("graph" = graph,
                  "parentnodename" =
                    list(
                         "parentnodename_hcst" = graph_hcst$parentnodename,
                         "parentnodename_obs" = graph_obs$parentnodename))
  }

  message("INFO  ", "[", Sys.time(), "]",
          " Provenance correctly generated for the Loading module")

  #Create directory to store de JSON files
  main_dir <- paste0(recipe$Run$output_dir, "/outputs", "/provenance/")
  if (!dir.exists(main_dir)) {
    dir.create(main_dir, recursive = TRUE)
  }

  #Name of the generated JSON according to recipe values
  recipe_model <- paste0("sys-",
                         gsub('\\.', '', recipe$Analysis$Datasets$System$name))
  recipe_split <- paste0("_ref-", recipe$Analysis$Datasets$Reference$name,
                         "_var-", recipe$Analysis$Variables$name,
                         "_reg-", recipe$Analysis$Region$name,
                         "_sdate-", recipe$Analysis$Time$sdate)

  json_name <- paste0("main_provenance", "_", recipe_model, recipe_split)

  #Convert from igraph to JSON format and store in the output directory
  graph2json(graph$graph, output.file = paste0(main_dir,
                                               json_name,  ".json"))
  
  return(graph)
}