library(markdown)

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")

md <- c(
	"# exploratory data analysis and models on the epi dataset",
	paste0("date: ", as.character(Sys.Date()), "  "),
	"",
	"## dataset and choices",
	# I regret my life choices
	paste0("- **file**: `", basename(ctx$data), "`"),
	paste0("- **region column**: `", ctx$region_col, "`"),
	paste0("- **response var**: `", ctx$response, "`"),
	paste0("- **regions**: `", ctx$region_a, "` vs `", ctx$region_b, "`"),
	"",
	"## 1) variable distributions",
	"### 1.1 boxplots and histograms (with density!)",
	paste0("![](", ctx$box_a, ")"),
	paste0("![](", ctx$box_b, ")"),
	paste0("![](", ctx$hist_a, ")"),
	paste0("![](", ctx$hist_b, ")"),
	"",
	"### 1.2 qq plot (two-sample)",
	paste0("![](", ctx$qq_fig, ")"),
	"",
	"## 2) linear models"
)

# Normalize data.frame because NOTHING WORKS
row_list <- function(x) {
	if (is.null(x)) return(list())
	if (is.data.frame(x)) {
		lapply(seq_len(nrow(x)), function(i) as.list(x[i, , drop = FALSE]))
	} else if (is.list(x)) {
		x
	} else {
		list()
	}
}

if (!is.null(ctx$ols) && length(ctx$ols)) {
	for (m in row_list(ctx$ols)) {
		md <- c(md,
		paste0("### ", m$name),
		sprintf("- **r²**: %.4f  |  **aic**: %.2f  |  **bic**: %.2f", m$r2, m$aic, m$bic),
		""
		)
	}
}

md <- c(md,
	"### 2.2 same models on one region (comparison)",
	if (!is.null(ctx$best_region_note)) ctx$best_region_note else "no note available.",
	"",
	"## 3) classification (knn, label = region)"
)

if (!is.null(ctx$knn) && length(ctx$knn)) {
	for (k in row_list(ctx$knn)) {
		md <- c(md,
		paste0("### ", k$tag),
		sprintf("- **k**: %d  |  **accuracy**: %.4f  |  **test n**: %d",
				k$k, k$accuracy, k$n_test),
		paste0("variables: `", paste(k$vars, collapse = ", "), "`"),
		paste0("![](", k$confusion_fig, ")"),
		""
		)
	}
}

# I hate markdown sometimes man
md <- gsub("/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/output/", "", md)

# writeLines(md, "/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/output/report.md")
# writeLines(jsonlite::toJSON(ctx, pretty = TRUE, auto_unbox = TRUE),
#            file.path(ctx$stats_dir, "summary.json"))

md_file <- "output/report.md"
html_file <- "output/report.html"
pdf_file <- "output/report.pdf"

setwd("/home/ion606/Desktop/Homework/Data Analytics/Assignments/Assignment II/")
markdownToHTML(
  md_file,
  html_file
)

message("done")
