library(dplyr)
library(ggplot2)

# Initialize an empty list to hold the summary data
all_summaries <- list()

if (grepl("^noncontextual", args[1])) {
  args_clean <- sub("^noncontextual", "", args)
}
args_clean <- sub("topNrevenue", "", args_clean)

current = 0

# Loop over all args and process each file
for (method in args) {
  current = current + 1
  path_file_name <- paste0('experiment_result/', method)
  df <- read.csv(path_file_name)
  colnames(df) <- c("epoch_num", "regret", "experiment_label")
  
  # Summarize by epoch
  summary_df <- df %>%
    group_by(epoch_num) %>%
    summarise(
      mean_regret = mean(regret),
      sd_regret = sd(regret),
      n = n(),
      se = sd_regret / sqrt(n),
      ci_lower = mean_regret - qt(0.975, df = n - 1) * se,
      ci_upper = mean_regret + qt(0.975, df = n - 1) * se,
      .groups = 'drop'
    )
  
  # Add method label
  summary_df$method <- args_clean[current]
  summary_df$method <- 
  
  # Store in list
  all_summaries[[method]] <- summary_df
}

# Combine all summaries into one data frame
final_df <- bind_rows(all_summaries)

# Plot
plots <- ggplot(final_df, aes(x = epoch_num, y = mean_regret, color = method, fill = method, group = method)) +
  geom_ribbon(
    aes(ymin = ci_lower, ymax = ci_upper),
    alpha = 0.2,
    color = NA,
    position = "identity"
  ) +
  geom_line() +
  labs(
    #title = "Average Regret Across Experiments",
    x = "T",
    y = "Regret"
  ) +
  theme_minimal() + 
  theme(
    legend.title = element_text(size = 18),  
    legend.text = element_text(size = 18)  
  ) + 
  theme(
    panel.background = element_rect(fill = "white", color = NA),  
    plot.background = element_rect(fill = "white", color = NA),
    axis.text = element_text(size = 16),       # axis tick labels
    axis.title = element_text(size = 16),      # axis titles
    plot.title = element_text(size = 18, face = "bold")  # plot title
  )


#print(plots)


words <- c("plots/",args, ".png")
file_name <- paste0(words, collapse = "")
ggsave(file_name, plots, width = 12, height = 8, dpi = 300)
