#!/usr/bin/env Rscript

args <- commandArgs(trailingOnly = FALSE)
file_arg <- args[grepl("^--file=", args)][1]
if (!is.na(file_arg)) {
  script_path <- sub("^--file=", "", file_arg)
  repo_root <- normalizePath(file.path(dirname(script_path), "..", ".."), mustWork = FALSE)
} else {
  repo_root <- normalizePath(getwd(), mustWork = TRUE)
}
if (!dir.exists(file.path(repo_root, "data"))) repo_root <- normalizePath(getwd(), mustWork = TRUE)

generated_dir <- Sys.getenv("PARTY2D_GENERATED_INPUT_DIR", file.path(repo_root, "_local", "generated-inputs"))
report_dir <- Sys.getenv("PARTY2D_REPORT_DIR", file.path(repo_root, "_local", "reports"))
dir.create(report_dir, recursive = TRUE, showWarnings = FALSE)

files <- c("text_data.csv", "expert.csv", "lr_data.csv", "union_mapping.csv", "party_families.csv")

file_info <- lapply(files, function(file) {
  committed <- file.path(repo_root, "data", file)
  generated <- file.path(generated_dir, file)
  committed_exists <- file.exists(committed)
  generated_exists <- file.exists(generated)
  committed_size <- if (committed_exists) file.info(committed)$size else NA_real_
  generated_size <- if (generated_exists) file.info(generated)$size else NA_real_
  identical_bytes <- committed_exists && generated_exists && isTRUE(tools::md5sum(committed) == tools::md5sum(generated))
  data.frame(
    file = file,
    committed_exists = committed_exists,
    generated_exists = generated_exists,
    committed_size = committed_size,
    generated_size = generated_size,
    identical_bytes = identical_bytes,
    stringsAsFactors = FALSE
  )
})

summary <- do.call(rbind, file_info)
report <- file.path(report_dir, "input_comparison.md")
lines <- c(
  "# Model input comparison",
  "",
  paste0("Generated: ", format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z")),
  "",
  "| File | Committed exists | Generated exists | Committed bytes | Generated bytes | Identical bytes |",
  "| --- | --- | --- | ---: | ---: | --- |",
  apply(summary, 1, function(row) {
    paste0("| ", row[["file"]], " | ", row[["committed_exists"]], " | ", row[["generated_exists"]], " | ", row[["committed_size"]], " | ", row[["generated_size"]], " | ", row[["identical_bytes"]], " |")
  })
)
writeLines(lines, report)
print(summary, row.names = FALSE)
message("Comparison report written to ", report)
