# Descriptive paired plot. Input and output stay on the local computer.
local({
  args <- commandArgs(trailingOnly = TRUE)
  if (length(args) != 5L) stop('Usage: Rscript --vanilla paired-figure-example.R INPUT.csv OUTPUT.svg REFERENCE CONTRAST Y_LABEL')
  input <- args[1]; output <- args[2]; reference <- args[3]; contrast <- args[4]; label <- args[5]
  if (!requireNamespace('ggplot2', quietly = TRUE) || !requireNamespace('svglite', quietly = TRUE)) stop('Install ggplot2 and svglite first')
  if (!file.exists(input) || dir.exists(input)) stop('Input CSV not found')
  link <- Sys.readlink(output)
  if (file.exists(output) || (!is.na(link) && nzchar(link))) stop('Output exists or is a symbolic link')
  if (!dir.exists(dirname(output)) || !grepl('\\.svg$', output, ignore.case = TRUE)) stop('Use a new .svg file in an existing directory')
  if (any(!nzchar(c(reference, contrast, label))) || reference == contrast || any(trimws(c(reference, contrast, label)) != c(reference, contrast, label))) stop('Provide two different conditions and an outcome label')
  d <- read.csv(input, colClasses = 'character', check.names = FALSE, na.strings = character(), stringsAsFactors = FALSE)
  if (!identical(names(d), c('id','group','value')) || nrow(d) == 0L) stop('CSV columns must be id,group,value')
  if (anyNA(d) || any(!nzchar(d$id)) || any(trimws(d$id) != d$id) || any(!d$group %in% c(reference, contrast))) stop('Check IDs and the two condition names')
  if (anyDuplicated(d[c('id','group')])) stop('Each ID must occur once in each condition')
  if (any(!grepl('^[+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][+-]?[0-9]+)?$', d$value))) stop('Values must be finite numbers')
  text_value <- d$value
  d$value <- suppressWarnings(as.numeric(text_value))
  mantissa <- sub('[eE].*$', '', text_value)
  if (any(!is.finite(d$value)) || any(d$value == 0 & grepl('[1-9]', mantissa))) stop('Non-finite or underflowed values are not supported')
  ids <- unique(d$id)
  if (length(ids) < 2L || nrow(d) != 2L * length(ids) || any(table(d$id, d$group) != 1L)) stop('At least two complete pairs are required')
  d$group <- factor(d$group, levels = c(reference, contrast))
  p <- ggplot2::ggplot(d, ggplot2::aes(x = group, y = value, group = id)) +
    ggplot2::geom_line(colour = '#A5BDB6', linewidth = 0.55) +
    ggplot2::geom_point(shape = 21, size = 3, stroke = 0.7, fill = 'white', colour = '#176A5E') +
    ggplot2::labs(x = NULL, y = label, caption = paste0('Complete pairs: ', length(ids))) +
    ggplot2::theme_classic(base_size = 12) + ggplot2::theme(plot.caption = ggplot2::element_text(hjust = 0))
  tmp <- tempfile(pattern = '.paired-', tmpdir = dirname(output), fileext = '.svg')
  on.exit(unlink(tmp), add = TRUE)
  ggplot2::ggsave(tmp, plot = p, device = svglite::svglite, width = 5, height = 4, units = 'in')
  # A same-directory hard link creates the final name without overwriting an existing file.
  if (!file.link(tmp, output)) stop('Could not create output without overwriting; check directory and filesystem')
  cat('Saved SVG with', length(ids), 'complete pairs.\n')
})
