source("/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/R/00_utils.R")
ctx <- jsonlite::fromJSON("/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/output/ctx.json")
df <- suppressMessages(readr::read_csv(ctx$data, show_col_types = FALSE))

va <- df |> dplyr::filter(.data[[ctx$region_col]] == ctx$region_a) |> dplyr::pull(all_of(ctx$response)) |> as.numeric()
vb <- df |> dplyr::filter(.data[[ctx$region_col]] == ctx$region_b) |> dplyr::pull(all_of(ctx$response)) |> as.numeric()

box_a_path  <- file.path(ctx$fig_dir, paste0("box_", sanitize(ctx$region_a), "_", sanitize(ctx$response), ".png"))
box_b_path  <- file.path(ctx$fig_dir, paste0("box_", sanitize(ctx$region_b), "_", sanitize(ctx$response), ".png"))
hist_a_path <- file.path(ctx$fig_dir, paste0("hist_", sanitize(ctx$region_a), "_", sanitize(ctx$response), ".png"))
hist_b_path <- file.path(ctx$fig_dir, paste0("hist_", sanitize(ctx$region_b), "_", sanitize(ctx$response), ".png"))
qq_path     <- file.path(ctx$fig_dir, paste0("qq_", sanitize(ctx$response), "_", sanitize(ctx$region_a), "_vs_", sanitize(ctx$region_b), ".png"))

save_plot(box_plot(va, paste0(ctx$response, " (", ctx$region_a, ")")), box_a_path)
save_plot(box_plot(vb, paste0(ctx$response, " (", ctx$region_b, ")")), box_b_path)
save_plot(hist_density_plot(va, paste0(ctx$response, " (", ctx$region_a, ")")), hist_a_path)
save_plot(hist_density_plot(vb, paste0(ctx$response, " (", ctx$region_b, ")")), hist_b_path)
qp <- qq_two_sample(va, vb, paste0("qq plot: ", ctx$region_a, " vs ", ctx$region_b))
if (!is.null(qp)) save_plot(qp, qq_path)

ctx$box_a <- box_a_path
ctx$box_b <- box_b_path
ctx$hist_a <- hist_a_path
ctx$hist_b <- hist_b_path
ctx$qq_fig <- qq_path
writeLines(jsonlite::toJSON(ctx, pretty = TRUE, auto_unbox = TRUE), "/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/output/ctx.json")
message("plots done")
