#!/usr/bin/env Rscript
# number_trace.R - check the numbers in a piece of text against source tables.
#
# Local and offline: base R only, no packages, no network. Nothing is sent anywhere.
# Same behaviour and same report layout as number_trace.py.
#
# Usage:
#   Rscript number_trace.R --source tables.txt [more_tables.txt ...] --text draft.txt
#           [--ignore 0.05,0.15] [--no-rounding] [--no-percent] [--verbose] [--out report.txt]
#
# What it does:
#   1. Pulls every number out of --text.
#   2. Looks for each one in the --source file(s), allowing leading zeros (.05 = 0.05),
#      thousands commas, minus-sign variants, rounding to the number of decimals the text
#      uses (half away from zero), and percent vs proportion (75.6% vs 0.756).
#   3. Lists numbers it could not find, and numbers found only by rounding or by a
#      percent/proportion conversion (so you can look at them).
#   4. Lists strong or interpretive phrases in the text that do not appear in the source.
#
# What it does NOT do: it proves a number appears somewhere in the source. It does not
# prove the number is in the right row, column, arm or table, or that the wording is right.
# A clean report is not a pass. See README.md.
#
# Exit status: 0 nothing flagged, 1 something flagged, 2 usage or file error.
# Licence: MIT.

VERSION <- "0.1.0"
TOL <- 1e-9

NUM_RE <- paste0("(?<![A-Za-z0-9_.])-?(?:\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.\\d+)?%?",
                 "|(?<![A-Za-z0-9_.])-?\\.\\d+%?")

LABEL_RES <- c(
  "(?i)\\b(?:tables?|figures?|listings?|appendix|sections?|slides?|pages?|pp?\\.)\\s*\\d+(?:[.\\-]\\d+)*",
  "(?<![A-Za-z0-9_.])\\d+-\\d+\\.\\d+\\b",
  "\\[\\d+(?:[,\\-]\\d+)*\\]"
)
LEADING_NUMBERING_RE <- "^\\s*\\d+(?:\\.\\d+)*\\.?\\s+(?=[A-Za-z])"

PHRASES <- c(
  "clinically (?:meaningful|relevant)",
  "\\b(?:statistically |clinically )?significant(?:ly)?\\b", "well[- ]tolerated",
  "no (?:new )?safety (?:signals?|concerns?|issues?)", "\\bsafe(?:ly)?\\b",
  "demonstrat(?:e|es|ed|ing)", "\\bprov(?:e|es|ed|en|ing)\\b", "\\bproof\\b", "\\balways\\b",
  "\\bnever\\b", "\\bnone\\b", "\\ball (?:patients|subjects|participants)\\b",
  "\\bno (?:patients|subjects|participants)\\b", "\\beffective(?:ness)?\\b",
  "\\bsuperior(?:ity)?\\b", "\\bbreakthrough\\b", "\\bcaus(?:e|es|ed|ing)\\b", "\\bdue to\\b",
  "\\brelated to\\b", "\\bimprov(?:e|es|ed|ement|ements|ing)\\b", "\\bworsen(?:s|ed|ing)?\\b",
  "\\bfavou?r(?:s|ed|able|ably)?\\b", "\\bbenefit(?:s|ed)?\\b", "\\bconsistent(?:ly)?\\b",
  "\\brobust\\b", "\\btrend(?:s|ing)?\\b", "\\bclearly\\b", "\\bconfirm(?:s|ed)?\\b",
  "\\bpromising\\b", "\\bremarkabl[ey]\\b", "\\bexcellent\\b", "\\bmostly\\b", "\\bmost\\b",
  "\\bfew\\b", "\\bmajority\\b", "\\bminimal\\b", "\\bnegligible\\b"
)
PHRASE_RES <- paste0("(?i)", PHRASES)

RANK <- c(exact = 0, rounded = 1, percent = 2, "percent+rounded" = 3)

blank_labels <- function(line, is_text) {
  line <- gsub("−", "-", line, fixed = TRUE)
  line <- gsub("–", "-", line, fixed = TRUE)
  line <- gsub("—", "-", line, fixed = TRUE)
  pats <- if (is_text) c(LABEL_RES, LEADING_NUMBERING_RE) else LABEL_RES
  for (rx in pats) {
    m <- gregexpr(rx, line, perl = TRUE)[[1]]
    if (m[1] == -1) next
    ml <- attr(m, "match.length")
    for (k in seq_along(m)) substr(line, m[k], m[k] + ml[k] - 1) <- strrep(" ", ml[k])
  }
  line
}

extract <- function(lines, is_text) {
  res <- list()
  for (i in seq_along(lines)) {
    cl <- blank_labels(lines[i], is_text)
    m <- gregexpr(NUM_RE, cl, perl = TRUE)[[1]]
    if (m[1] == -1) next
    ml <- attr(m, "match.length")
    for (k in seq_along(m)) {
      tok <- substr(cl, m[k], m[k] + ml[k] - 1)
      pct <- substring(tok, nchar(tok)) == "%"
      t <- gsub(",", "", sub("%$", "", tok), fixed = TRUE)
      dec <- if (grepl(".", t, fixed = TRUE)) nchar(strsplit(t, ".", fixed = TRUE)[[1]][2]) else 0
      res[[length(res) + 1]] <- list(line = i, start = m[k] - 1, end = m[k] - 1 + ml[k],
        token = tok, value = as.numeric(t), decimals = dec, pct = pct,
        key = paste0(t, if (pct) "%" else ""))
    }
  }
  res
}

sgn <- function(x) if (x >= 0) 1 else -1
scaled_int <- function(x, d) floor(abs(x) * 10^d + 0.5) * sgn(x)
half_up <- function(x, d) floor(abs(x) * 10^d + 0.5 + 1e-7) * sgn(x)

candidates <- function(src, use_pct) {
  s <- src$value; ds <- src$decimals
  out <- list(list(kind = "exact", c = s, dc = ds, needs = NA))
  if (use_pct) {
    if (abs(s) <= 1) out[[length(out) + 1]] <- list(kind = "percent", c = s * 100, dc = max(ds - 2, 0), needs = TRUE)
    if (s >= 0 && s <= 100) out[[length(out) + 1]] <- list(kind = "percent", c = s / 100, dc = ds + 2, needs = FALSE)
  }
  out
}

best_match <- function(num, sources, rounding, use_pct, negate = FALSE) {
  t <- if (negate) -num$value else num$value
  dt <- num$decimals
  best <- NULL; best_rank <- Inf
  for (j in seq_along(sources)) {
    for (cd in candidates(sources[[j]], use_pct)) {
      if (!is.na(cd$needs) && cd$needs && !num$pct) next
      if (!is.na(cd$needs) && !cd$needs && num$pct) next
      if (cd$dc == dt && scaled_int(cd$c, cd$dc) == scaled_int(t, dt)) {
        k <- cd$kind
      } else if (rounding && cd$dc > dt && half_up(cd$c, dt) == scaled_int(t, dt)) {
        k <- if (cd$kind == "exact") "rounded" else "percent+rounded"
      } else next
      if (RANK[[k]] < best_rank) { best <- list(kind = k, idx = j); best_rank <- RANK[[k]] }
    }
  }
  best
}

context <- function(line, start, end, width = 25) {
  a <- max(0, start - width); b <- min(nchar(line), end + width)
  s <- gsub("\t", " ", substr(line, a + 1, b), fixed = TRUE)
  trimws(gsub(" +", " ", s))
}

read_lines <- function(p) {
  x <- readLines(p, encoding = "UTF-8", warn = FALSE)
  if (length(x) > 0) x[1] <- sub("^﻿", "", x[1])
  x
}

run_trace <- function(source_paths, text_path, ignore, rounding, use_pct, verbose) {
  src_names <- basename(source_paths)
  sources <- list(); seen <- character(0); src_text <- character(0)
  for (pi in seq_along(source_paths)) {
    lines <- read_lines(source_paths[pi])
    src_text <- c(src_text, lines)
    for (n in extract(lines, FALSE)) {
      if (!(n$key %in% seen)) {
        seen <- c(seen, n$key)
        n$where <- sprintf("%s line %d", src_names[pi], n$line)
        sources[[length(sources) + 1]] <- n
      }
    }
  }
  tlines <- read_lines(text_path)
  nums <- extract(tlines, TRUE)
  all_src_text <- paste(src_text, collapse = "\n")

  counts <- c(exact = 0, percent = 0, rounded = 0, allowed = 0, notfound = 0)
  notfound <- list(); look <- list(); found_rows <- list(); weak <- 0
  for (n in nums) {
    if (length(ignore) > 0 && any(abs(n$value - ignore) < TOL)) { counts["allowed"] <- counts["allowed"] + 1; next }
    m <- best_match(n, sources, rounding, use_pct)
    if (is.null(m)) {
      counts["notfound"] <- counts["notfound"] + 1
      note <- ""
      flip <- best_match(n, sources, FALSE, use_pct, negate = TRUE)
      if (!is.null(flip)) {
        fs <- sources[[flip$idx]]
        note <- sprintf("  [source has \"%s\" with the opposite sign (%s)]", fs$token, fs$where)
      }
      notfound[[length(notfound) + 1]] <- list(n = n, note = note)
      next
    }
    src <- sources[[m$idx]]
    if (m$kind == "exact") {
      counts["exact"] <- counts["exact"] + 1
      if (n$decimals == 0 && !n$pct && abs(n$value) < 10) weak <- weak + 1
    } else {
      key <- if (m$kind == "percent") "percent" else "rounded"
      counts[key] <- counts[key] + 1
      look[[length(look) + 1]] <- list(n = n, kind = m$kind, src = src)
    }
    if (verbose) found_rows[[length(found_rows) + 1]] <- list(n = n, kind = m$kind, src = src)
  }

  ph_line <- integer(0); ph_start <- integer(0); ph_text <- character(0); ph_ctx <- character(0)
  for (i in seq_along(tlines)) {
    raw <- tlines[i]
    for (rx in PHRASE_RES) {
      if (grepl(rx, all_src_text, perl = TRUE)) next
      m <- gregexpr(rx, raw, perl = TRUE)[[1]]
      if (m[1] == -1) next
      ml <- attr(m, "match.length")
      for (k in seq_along(m)) {
        ph_line <- c(ph_line, i); ph_start <- c(ph_start, m[k] - 1)
        ph_text <- c(ph_text, substr(raw, m[k], m[k] + ml[k] - 1))
        ph_ctx <- c(ph_ctx, context(raw, m[k] - 1, m[k] - 1 + ml[k], 30))
      }
    }
  }
  ord <- order(ph_line, ph_start)

  distinct <- length(unique(vapply(nums, function(n) n$key, "")))
  o <- character(0)
  add <- function(...) o <<- c(o, sprintf(...))
  add("number_trace %s (local, offline)", VERSION)
  add("source files: %s", paste(src_names, collapse = ", "))
  add("text file: %s", basename(text_path))
  add("rounding: %s   percent/proportion: %s", if (rounding) "on" else "off", if (use_pct) "on" else "off")
  add("")
  add("SUMMARY")
  add("numbers in text: %d (%d distinct)", length(nums), distinct)
  add("  found exactly: %d", counts[["exact"]])
  add("  found as percent/proportion only: %d", counts[["percent"]])
  add("  found after rounding only: %d", counts[["rounded"]])
  add("  allowed with --ignore: %d", counts[["allowed"]])
  add("  NOT FOUND: %d", counts[["notfound"]])
  add("  (single-digit integers found exactly, easy to match by chance: %d)", weak)
  add("strong or interpretive phrases not in the source: %d", length(ph_text))
  add("")
  add("NOT FOUND IN SOURCE")
  if (length(notfound) > 0) {
    for (r in notfound) {
      n <- r$n
      add("  line %d  \"%s\"  ...%s...%s", n$line, n$token,
          context(tlines[n$line], n$start, n$end), r$note)
    }
  } else add("  none")
  add("")
  add("FOUND ONLY BY ROUNDING OR PERCENT/PROPORTION (check these by eye)")
  if (length(look) > 0) {
    for (r in look) add("  line %d  \"%s\"  matches source \"%s\" (%s) by %s",
                        r$n$line, r$n$token, r$src$token, r$src$where, r$kind)
  } else add("  none")
  add("")
  add("STRONG OR INTERPRETIVE PHRASES NOT IN THE SOURCE")
  if (length(ph_text) > 0) {
    for (k in ord) add("  line %d  \"%s\"  ...%s...", ph_line[k], ph_text[k], ph_ctx[k])
  } else add("  none")
  if (verbose) {
    add("")
    add("ALL MATCHED NUMBERS")
    for (r in found_rows) add("  line %d  \"%s\"  -> \"%s\" (%s) %s",
                              r$n$line, r$n$token, r$src$token, r$src$where, r$kind)
  }
  add("")
  add("Limits: a number found here appears somewhere in the source. This does not show it is the")
  add("right number, in the right row, column, arm or table, or that the wording is correct.")
  list(report = paste0(paste(o, collapse = "\n"), "\n"),
       flagged = counts[["notfound"]] > 0 || length(ph_text) > 0)
}

main <- function(argv) {
  usage <- function(msg) { cat("number_trace: ", msg, "\n", sep = "", file = stderr()); quit(status = 2) }
  src <- character(0); txt <- NULL; ignore <- numeric(0); out <- NULL
  rounding <- TRUE; use_pct <- TRUE; verbose <- FALSE
  i <- 1; mode <- ""
  while (i <= length(argv)) {
    a <- argv[i]
    if (a == "--source") mode <- "source"
    else if (a == "--text") { txt <- argv[i + 1]; i <- i + 1; mode <- "" }
    else if (a == "--ignore") {
      v <- strsplit(argv[i + 1], ",", fixed = TRUE)[[1]]; i <- i + 1; mode <- ""
      v <- trimws(v); v <- v[nzchar(v)]
      ignore <- suppressWarnings(as.numeric(v))
      if (any(is.na(ignore))) usage("--ignore needs comma-separated numbers")
    }
    else if (a == "--out") { out <- argv[i + 1]; i <- i + 1; mode <- "" }
    else if (a == "--no-rounding") rounding <- FALSE
    else if (a == "--no-percent") use_pct <- FALSE
    else if (a == "--verbose") verbose <- TRUE
    else if (mode == "source" && !startsWith(a, "--")) src <- c(src, a)
    else usage(paste("unknown argument:", a))
    i <- i + 1
  }
  if (length(src) == 0 || is.null(txt) || is.na(txt)) usage("need --source FILE [FILE ...] and --text FILE")
  for (p in c(src, txt)) if (!file.exists(p)) usage(paste("cannot read file:", p))
  res <- run_trace(src, txt, ignore, rounding, use_pct, verbose)
  if (!is.null(out)) {
    con <- file(out, "wb"); writeBin(charToRaw(enc2utf8(res$report)), con); close(con)
  } else cat(res$report)
  quit(status = if (res$flagged) 1 else 0)
}

if (!interactive()) main(commandArgs(trailingOnly = TRUE))
