args <- commandArgs(trailingOnly = TRUE)
fixture <- if (length(args)) args[[1L]] else "csv-identifier-check.csv"

sites_inferred <- read.csv(fixture)
sites_text <- read.csv(fixture, colClasses = c(ExternalID = "character"))
quoted_csv <- paste(capture.output(write.csv(sites_text, row.names = FALSE)),
                    collapse = "\n")
quoted_inferred <- read.csv(text = quoted_csv)
quoted_text <- read.csv(text = quoted_csv,
                       colClasses = c(ExternalID = "character"))
payments <- data.frame(
  PaymentID = c("P-01", "P-02", "P-03"),
  ExternalID = c("001", "1", "999"),
  Amount = c(25L, 75L, 50L)
)

join_sites <- function(payment_rows, site_rows) {
  merge(payment_rows, site_rows[c("ExternalID", "Site")],
        by = "ExternalID", all.x = TRUE)
}

payments_numeric <- transform(payments, ExternalID = as.integer(ExternalID))
joined_inferred <- join_sites(payments_numeric, sites_inferred)
joined_text <- join_sites(payments, sites_text)
joined_late_cast <- join_sites(
  transform(payments_numeric, ExternalID = as.character(ExternalID)),
  sites_text
)

stopifnot(
  identical(sites_inferred$ExternalID, c(1L, 1L, 10L)),
  identical(sites_text$ExternalID, c("001", "1", "010")),
  identical(quoted_inferred$ExternalID, sites_inferred$ExternalID),
  identical(quoted_text$ExternalID, sites_text$ExternalID),
  nrow(joined_inferred) == 5L,
  sum(joined_inferred$Amount) == 250L,
  nrow(joined_text) == 3L,
  sum(joined_text$Amount) == 150L,
  identical(joined_text$Site[joined_text$PaymentID == "P-01"], "North workshop"),
  identical(joined_text$Site[joined_text$PaymentID == "P-02"], "East branch"),
  is.na(joined_text$Site[joined_text$PaymentID == "P-03"]),
  nrow(joined_late_cast) == 3L,
  sum(joined_late_cast$Amount) == 150L,
  identical(joined_late_cast$Site[joined_late_cast$PaymentID == "P-01"], "East branch")
)

summarize_join <- function(rows) {
  data.frame(
    Rows = nrow(rows),
    Amount = sum(rows$Amount),
    P01 = paste(sort(rows$Site[rows$PaymentID == "P-01"]), collapse = " / ")
  )
}

cat(R.version.string, "\n")
cat("Quoted IDs with default import:", quoted_inferred$ExternalID, "\n")
cat("Quoted IDs with character import:", quoted_text$ExternalID, "\n")
print(rbind(
  "Numeric keys" = summarize_join(joined_inferred),
  "Text from import" = summarize_join(joined_text),
  "Cast back to text after import" = summarize_join(joined_late_cast)
))
