# WARNING - Generated by {fusen} from dev/flat_simulate_treatment.Rmd: do not edit by hand # nolint: line_length_linter.

#' Calculate Wide-Format Treatment Scheme Events
#' 
#' This function and returns the results in a wide-format data frame.
#' 
#' This function does the same thing as kwb.qmra::get_scheme_events_wide(),
#' but it is bundled with *ambre* to avoid a hard dependency on the 
#' unmaintained package.
#' 
#' @param config A configuration object containing treatment scheme information.
#' @param treatment_events_wide A data frame in wide format containing treatment events
#'   with columns for each treatment ID and log-reduction values.
#' 
#' @importFrom stats setNames
#' 
#' @return A data frame with columns for event ID, pathogen group, and one column
#'   for each treatment scheme containing the sum of log-reduction values for that scheme.
#' @references
#'   Sonnenberg H (2024). kwb.utils: General Utility Functions Developed at KWB. R package version 0.15.0
#'   URL: \url{https://github.com/kwb-r/kwb.utils}
#'   (MIT Licence)
#' @export
#' @examples
#' # Example usage of get_scheme_events_wide
#' scenario_test <- create_scenario(
#'   system.file("input_1culture_2pop.xlsx", package = "ambre")
#' )
#' scenario_updated <- update_pathogen(scenario = scenario_test,
#'  pathoName = c("Campylobacter jejuni", "Rotavirus"))
#' config <- scenario_updated$config[[1]]
#'
#' # Simulate treatment data
#' treatment_data <- get_treatment_data(config$treatment$processes, n_repeatings = 5, n_events = 3)
#'
#' treatment_events_wide <- treatment_data$events |> tidyr::spread(
#'       key = TreatmentID,
#'       value = logreduction
#'     )
#'
#' # Apply get_scheme_events_wide
#' scheme_events_wide <- get_scheme_events_wide(config, treatment_events_wide)
#'
#' # Print results
#' print(scheme_events_wide)
get_scheme_events_wide <- function(config, treatment_events_wide){
  schemes <- config$treatment$schemes
  
  schemeIDs <- unique(schemes$TreatmentSchemeID)
  
  schemes_events_wide <- data.frame()

  for (schemeID in schemeIDs) {
    
    is_scheme <- schemes$TreatmentSchemeID == schemeID
    
    scheme_treatmentIDs <- unique(schemes$TreatmentID[is_scheme])
    
    event_row_sums <- rowSums(
      treatment_events_wide[, as.character(scheme_treatmentIDs), drop = FALSE]
    )

    if (schemeID == schemeIDs[1]) {
      
      schemes_events_wide <- cbind(
        treatment_events_wide[, c("eventID", "PathogenGroup")],
        event_row_sums,
        row.names = NULL
      )
      
    } else {
      
      schemes_events_wide <- cbind(
        schemes_events_wide,
        event_row_sums,
        row.names = NULL
      )
    }
  }
  
  stats::setNames(schemes_events_wide, c(
    "eventID", "PathogenGroup", paste0("scheme_", schemeIDs)
  ))
}
