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

#' Run economic analysis
#' 
#' Calculate annual cost and total investment fees for simulated management risk scenario
#' @param scenario data.frame scenario obtained with create_scenario function
#' @param price_per_m3 numeric, water price in euro per cubic meter
#' @param membership_fee numeric annual membership fee in euro per hectare
#' @param grant numeric amount of the grant in percentage
#' @param initialSituation boolean, TRUE to simulate initial situation cost, FALSE to simulate supplementary process cost
#' @param allocation_key numeric allocation key, NULL by default
#' @return all_plots
#' 
#' @export
#' @examples
#' scenario <- create_scenario(
#'   system.file("input_1culture_2pop.xlsx", package = "ambre")
#' )
#' run_economic_analysis(scenario = scenario,
#'                       price_per_m3 = 0.1, 
#'                       membership_fee = 200, 
#'                       grant = 0.5,
#'                       initialSituation = TRUE)
#' run_economic_analysis(scenario = scenario,
#'                       price_per_m3 = 0.1, 
#'                       membership_fee = 200, 
#'                       grant = 0.5,
#'                       initialSituation = FALSE)
#'
#' crop <- scenario$CropName
#' allocation_custom <- data.frame(CropName = crop,
#'                                 allocation = c(0.5, 0.5))
#' run_economic_analysis(scenario = scenario,
#'                       price_per_m3 = 0.1, 
#'                       membership_fee = 200, 
#'                       grant = 0,
#'                       initialSituation = TRUE,
#'                       allocation_key = allocation_custom)
run_economic_analysis <- function(scenario, price_per_m3, membership_fee, grant, initialSituation, allocation_key = NULL){
  irrigation_need <- irrigation_need_calculation(scenario = scenario)
  
  # 1. Water price

  irrigation_need_with_waterprice <- water_price(scenario = irrigation_need,
              price_per_m3 = price_per_m3,
              membership_fee = membership_fee)
  
  
  # 2. Mesure collective
  if (all(!is.na(irrigation_need_with_waterprice$CollectiveTreatmentID))) {
    if (is.null(allocation_key)){
      irrigation_need_with_collectivecost <- collective_treatment_cost_calculation(
                        scenario = irrigation_need_with_waterprice,
                        grant = grant
                        )
    } else {
      irrigation_need_with_collectivecost <- collective_treatment_cost_calculation(
                        scenario = irrigation_need_with_waterprice,
                        grant = grant,
                        allocation_key = allocation_key)
    }
  
} else {
  irrigation_need_with_collectivecost <- list(scenario = irrigation_need_with_waterprice,
                                                    allocation_key = NA)
  irrigation_need_with_collectivecost$scenario <-
  irrigation_need_with_collectivecost$scenario |>
  mutate(
    capex_collective_treatment = NA,
    collective_opex = NA,
    loan_asa = NA
  )
}
  
  
  # 3. Mesure individuelle : opex et capex
  
  if(initialSituation == TRUE){
    irrigation_need_with_mesurecost <- process_cost_calculation(scenario = irrigation_need_with_collectivecost$scenario, 
                                                              membership_fee = membership_fee, 
                                                              charge = price_per_m3,
                                                              initialSituation = TRUE)
  }
  else if(initialSituation == FALSE){
    irrigation_need_with_mesurecost <- process_cost_calculation(scenario = irrigation_need_with_collectivecost$scenario, 
                                                              membership_fee = membership_fee, 
                                                              charge = price_per_m3,
                                                              initialSituation = FALSE)
  }
  
  
  
  irrigation_need_long <- irrigation_need_with_mesurecost |>
    select(c(CropName, annual_membership_fee, loan_asa, 
             water_charge, collective_opex, opex_supplementaryProcess, capex_supplementaryProcess_20y)) |>
    rename("Annual membership fee" = annual_membership_fee,
           "Water price" = water_charge,
           "Operational cost collective process" = collective_opex,
           "Investment collective process (20-year loan)" = loan_asa,
           "Operational cost individual process" = opex_supplementaryProcess,
           "Investment individual process (20-year loan)" = capex_supplementaryProcess_20y)|>
    pivot_longer(cols = !CropName, names_to = "cost_type", values_to = "value") |>
    mutate(
    cost_type = factor(
      cost_type,
      levels = c(
        "Water price",
        "Annual membership fee",
        "Operational cost collective process",
        "Investment collective process (20-year loan)",
        "Operational cost individual process",
        "Investment individual process (20-year loan)"
      )
    )
  )|>
    unique()
  
  
    plot_annual <- ggplot(irrigation_need_long, aes(x = CropName, 
                                     y = value, 
                                     fill = cost_type, 
                                     label = value))+
      geom_bar(stat = "identity") +
      geom_text(size = 3, position = position_stack(vjust = 0.5)) +
      scale_fill_manual(
        values = c(
          "Water price" = "palegreen4",
        "Annual membership fee" = "palegreen",
        "Operational cost collective process"  = "#fedc7f",
        "Investment collective process (20-year loan)" = "#d28433",
        "Operational cost individual process"  = "#9bdde1",
        "Investment individual process (20-year loan)" = "#167779"
        )
      )+
      labs(fill = "Cost Type", y = "Annual cost (EUR/year)") + 
      theme_minimal()
  if(initialSituation == TRUE){
    result <- list(annual = plot_annual,
                      allocation_key = irrigation_need_with_collectivecost$allocation_key)
  }
  
  else if(initialSituation == FALSE){
    total_investment <- irrigation_need_with_mesurecost |>
    select(c(CropName, capex_supplementaryProcess, capex_collective_treatment)) |>
    rename("Investment collective process" = capex_collective_treatment,
           "Investment individual process" = capex_supplementaryProcess) |>
    pivot_longer(cols = !CropName, names_to = "cost_type", values_to = "value") |>
    unique()
  
    plot_total <- ggplot(total_investment, aes(x = CropName, 
                                   y = value, 
                                   fill = cost_type, 
                                   label = value))+
    geom_bar(stat = "identity") +
    geom_text(size = 3, position = position_stack(vjust = 0.5)) +
    scale_fill_manual(
      values = c(
        "Investment collective process" = "#d28433",
        "Investment individual process" = "#167779"
      )
    )+ 
    labs(fill = "Cost Type", y = "Total cost (EURO)") + 
    theme_minimal() + 
    theme(legend.position = "bottom")
  
  
  result <- list(annual = plot_annual,
                   total_investement = plot_total,
                   allocation_key = irrigation_need_with_collectivecost$allocation_key)
  }
  return(result)
    
}
