#' @title Directed metadata graph construction for SUNSET's Aggregation module.
#' @description Generate provenance for the Aggregation operation within a
#'              SUNSET workflow.
#' @param recipe Configuration file specifying parameters.
#' @param data s2dv_cube object generated by SUNSET's Loading.R function.
#' @param type Type of data: "fcst" for forecast, "hcst" for hindcast,
#'             or "obs" for observational data.
#' @details  Function to perform provenance aggregation for a specific dataset type.
#            This function updates a provenance graph by defining and adding temporal aggregation steps
#            based on a SUNSET recipe and the data aggregated in the Aggregation module. The graph is enriched 
#            with nodes and edges representing the temporal aggregation process, including metadata for each 
#            aggregation period and its temporal extent.
#' @references This function is based on the semantics outlined
#'             in the Datasource ontology within the Metaclip Framework
#'             (available at \url{http://www.metaclip.org/}).
#' @references https://earth.bsc.es/gitlab/es/sunset/-/tree/Dev-Provenance?ref_type=heads 
#'            Documentation for SUNSET's provenance generation. 
#' @import igraph


prov_aggregation <- function(recipe, data, graph, type){
  #Define key terms for the graph
  i <- switch(type,
              "fcst" = "parentnodename_fcst",
              "hcst" = "parentnodename_hcst",
              "obs" = "parentnodename_obs")
  parentnodename <- graph$parentnodename[[i]]
  graph <- graph$graph
  method <- recipe$Analysis$Workflow$Time_aggregation$method
  ini <- recipe$Analysis$Workflow$Time_aggregation$ini
  end <- recipe$Analysis$Workflow$Time_aggregation$end
  
  #Aggregation step
  aggregation.nodename <- paste0("Aggregation_", type)

  aggregation_descriptions <- paste0("from month/week ", ini, " to month/week ", end, collapse = ", ")
  description <- paste0("Temporal aggregation. \nMethod: ", method, 
                      ". \nPeriods: ", aggregation_descriptions)

  graph <- add_vertices_sunset(graph,
                                 nv = 1,
                                 name = aggregation.nodename,
                                 label = "Aggregation",
                                 className = "ds:Aggregation",
                                 attr = list("dc:description" = description)
                                 )

  graph <- add_edges(graph,
                     c(getNodeIndexbyName(graph, parentnodename),
                         getNodeIndexbyName(graph, aggregation.nodename)),
                       label = "ds:hadAggregation")

  var <- recipe$Analysis$Variables$name
  var.freq <- recipe$Analysis$Variables$freq 
  time <- data[[type]]$attr$Dates
  j <- length(data[[type]]$coords$syear)

  for (i in 1:length(ini)) {
    
    time_period <- time[(1 + j*(i-1)) : (j*i)]
    time_period <- paste(format(time_period, format = "%Y-%m-%d"), collapse = " ")
    timeper.nodename <- paste0("TemporalPeriod_", type, "_Aggregation_", i)
    description <- paste0("Date values for aggregation of week/mont ", 
                          ini[i], " with month/week ", end[i], ". The aggregation is stored 
                          in this date values")
    graph <- add_vertices(graph,
                          nv = 1,
                          name = timeper.nodename,
                          label = "TemporalPeriod",
                          className = "ds:TemporalPeriod",
                          description = "Temporal period for each aggregated section",
                          attr = list("prov:atTime" = time_period,
                                      "dc:description"= description))

  graph <- add_edges(graph,
                       c(getNodeIndexbyName(graph, aggregation.nodename),
                         getNodeIndexbyName(graph, timeper.nodename)),
                       label = "ds:hasValidTemporalExtent")
  }

  #start.time <- format(data[[type]]$attr$time_bounds$start, format = "%Y-%m-%d")
  #end.time <- format(data[[type]]$attr$time_bounds$end, format = "%Y-%m-%d")
  #start.time <- paste(start.time, collapse = " ")
  #end.time <- paste(end.time, collapse = " ")
  
  
  # if (var.freq == "monthly_mean" || type == "fcst") {
  #   for (i in 1:length(data[[type]]$coords$syear)){
  #     start.time <- append(start.time, format(data[[type]]$attrs$Dates,
  #                                             format = "%Y-%m-%d %Z")[[i]])
  #     j <-
  #       ((length(data[[type]]$coords$time) - 1)
  #       * length(data[[type]]$coords$syear) + i)
  #     end.time <- append(end.time, format(data[[type]]$attrs$Dates,
  #                                         format = "%Y-%m-%d %Z")[[j]])
  #   }
  #
  #   freq <- switch(var.freq,
  #                  "monthly_mean" = "Monthly Mean",
  #                  "weekly_mean" = "Weekly Mean")
  #
  #   start.time <- paste(start.time, collapse = " ")
  #   end.time <- paste(end.time, collapse = " ")
  #   graph <- add_vertices(graph,
  #                         nv = 1,
  #                         name = timeper.nodename,
  #                         label = "TemporalPeriod",
  #                         className = "ds:TemporalPeriod",
  #                         description = "Encode metadata of Temporal Periods",
  #                         attr = list("prov:startedAtTime" = start.time,
  #                                       "prov:endedAtTime" = end.time,
  #                                       "ds:hasTimeFrequency" = freq))
  #
  #   graph <- add_edges(graph,
  #                      c(getNodeIndexbyName(graph, aggregation.nodename),
  #                        getNodeIndexbyName(graph, timeper.nodename)),
  #                      label = "ds:hasValidTemporalExtent")
  #   
  # } else if (var.freq == "weekly_mean" && (type == "hcst" || type == "obs")) {
  #   sdates <- dates2load(recipe, recipe$Run$logger)
  #   years <- as.numeric(recipe$Analysis$Time$hcst_end) - as.numeric(recipe$Analysis$Time$hcst_start) + 1  
  #   time_period <- list()
  #   for (i in 1:years){
  #     year_week_windows <- sdates$hcst[,,i]
  #       for (j in 1:recipe$Analysis$Time$sweek_window) {
  #         week_window <- year_week_windows[j,]
  #         formatted_dates <- format(as.POSIXct(week_window, format="%Y%m%d"), "%Y-%m-%d 09:00:00")
  #         week_window_dates <- unlist(paste0("(", paste(formatted_dates, collapse = " - "), ")"))
  #         time_period[[length(time_period) + 1]] <- week_window_dates
  #       }
  #
  #   }
  #   
  #   timeper.nodename <- paste0("TemporalPeriod_", type, "_Aggregation")
  #   graph <- add_vertices(graph,
  #                         nv = 1,
  #                         name = timeper.nodename,
  #                         label = "TemporalPeriod",
  #                         className = "ds:TemporalPeriod",
  #                         description = "Encode metadata of Temporal Periods",
  #                         attr = list("prov:value" = paste(unlist(time_period), collapse = " "),
  #                                     "ds:hasTimeFrequency" = var.freq))
  #
  #   graph <- add_edges(graph,
  #                      c(getNodeIndexbyName(graph, aggregation.nodename),
  #                        getNodeIndexbyName(graph, timeper.nodename)),
  #                      label = "ds:hasValidTemporalExtent")
  # }

    

    #New horizontal extent (Now we only have temporal aggregation)
    #var <- unlist(strsplit(recipe$Analysis$Variables$name,
    #                             ",\\s*"))[[1]]
    #refgraph <- get_spatial_extent(data, type, var, Aggr = TRUE)
    #graph <- my_union_graph(graph, refgraph$graph)
    #graph <- add_edges(graph,
    #                  c(getNodeIndexbyName(graph, aggregation.nodename),
    #                    getNodeIndexbyName(graph, refgraph$parentnodename)),
    #                  label = "ds:hasHorizontalExtent")

  return(list("graph" = graph, "parentnodename" = aggregation.nodename))

}