# The R runner's helpers – R code that describes what's in the session as plain JSON text (rrun/runner.js).
# Copyright (C) 2026 the Caboodle authors. GNU General Public License version 3 (or later): LICENSES/GPL-3.0.txt.
.cab <- new.env()
local({
  # a JSON string from R text
  q <- function(s) {
    if (!length(s)) return(character(0))  # (paste0 would make one "" of nothing)
    s <- enc2utf8(as.character(s))
    s[is.na(s)] <- "NA"
    s <- gsub("\\", "\\\\", s, fixed = TRUE)
    s <- gsub("\"", "\\\"", s, fixed = TRUE)
    s <- gsub("\n", "\\n", s, fixed = TRUE)
    s <- gsub("\r", "\\r", s, fixed = TRUE)
    s <- gsub("\t", "\\t", s, fixed = TRUE)
    s <- gsub("[[:cntrl:]]", " ", s)
    paste0("\"", s, "\"")
  }
  # a column as JSON values (numbers stay numbers; missing values are null)
  col <- function(x) {
    if (is.factor(x)) x <- as.character(x)
    if (is.logical(x)) return(ifelse(is.na(x), "null", ifelse(x, "true", "false")))
    if (is.numeric(x) && !inherits(x, c("Date", "POSIXt", "difftime"))) return(ifelse(is.finite(x), formatC(x, digits = 15, format = "g", flag = ""), "null"))
    v <- if (is.list(x)) vapply(x, function(e) paste(format(e), collapse = ", "), "") else format(x)
    ifelse(is.na(x) & !is.list(x), "null", q(trimws(v)))
  }
  kind <- function(x) if (is.factor(x)) "factor" else if (inherits(x, "Date")) "date" else if (inherits(x, "POSIXt")) "datetime" else if (is.logical(x)) "logical" else if (is.integer(x)) "integer" else if (is.numeric(x)) "number" else if (is.character(x)) "text" else class(x)[1]
  one <- function(n, x) {
    d <- dim(x)
    prev <- tryCatch(paste(utils::capture.output(utils::str(x, max.level = 0, give.attr = FALSE, vec.len = 3, nchar.max = 80))[1], collapse = ""), error = function(e) "")
    paste0("{\"name\":", q(n), ",\"class\":", q(class(x)[1]),
      ",\"kind\":", q(if (is.data.frame(x)) "data" else if (is.function(x)) "function" else if (is.matrix(x)) "matrix" else if (is.list(x)) "list" else "value"),
      ",\"dims\":", q(if (is.null(d)) length(x) else paste(d, collapse = " × ")),
      ",\"size\":", q(format(utils::object.size(x), units = "auto")),
      ",\"preview\":", q(prev), "}")
  }
  # the objects in the global environment
  env <- function() {
    ns <- ls(globalenv(), sorted = TRUE)
    paste0("[", paste(vapply(ns, function(n) one(n, get(n, envir = globalenv())), ""), collapse = ","), "]")
  }
  # rows from .. to of a data frame (or matrix), its columns and how many rows it has
  table <- function(name, from = 1, to = 200, sort = "", desc = FALSE) {
    x <- if (!is.null(.cab$views[[name]])) .cab$views[[name]] else get(name, envir = globalenv())
    if (is.matrix(x)) x <- as.data.frame(x)
    if (!is.data.frame(x)) stop(name, " isn't a data frame")
    n <- nrow(x)
    idx <- seq_len(n)
    if (nzchar(sort) && sort %in% names(x)) idx <- order(x[[sort]], decreasing = desc, na.last = TRUE)
    from <- max(1, from); to <- min(n, to)
    rows <- if (to >= from) idx[from:to] else integer(0)
    part <- x[rows, , drop = FALSE]
    cols <- lapply(part, col)
    body <- if (length(rows)) paste0("[", do.call(paste, c(cols, sep = ",")), "]") else character(0)
    rn <- attr(x, "row.names")
    names_ <- if (is.character(rn)) q(rn[rows]) else as.character(rows)
    paste0("{\"total\":", n, ",\"columns\":[", paste0("{\"name\":", q(names(x)), ",\"type\":", q(vapply(x, kind, "")), "}", collapse = ","), "]",
      ",\"rowNames\":[", paste(names_, collapse = ","), "]",
      ",\"rows\":[", paste(body, collapse = ","), "]}")
  }
  # runs code as the console does: each expression in turn, its value printed when visible; Stop (an interrupt) ends it
  # here – caught in R, so webR's evaluation carries on – and an error ends it with the error as R words it
  run <- function(code) {
    exprs <- tryCatch(parse(text = code, keep.source = FALSE), error = function(e) {
      stop(simpleError(sub("^<text>:", "line ", conditionMessage(e))))
    })
    tryCatch({
      for (e in exprs) {
        r <- withVisible(eval(e, envir = globalenv()))
        if (r$visible) print(r$value)
      }
      invisible(NULL)
    }, interrupt = function(i) {
      cat("\nStopped\n")
      invisible(NULL)
    })
  }
  # is the code a whole expression ("ok"), unfinished ("incomplete") or wrong ("error")?
  check <- function(code) tryCatch({ parse(text = code, keep.source = FALSE); "ok" }, error = function(e) if (grepl("unexpected end of input|INCOMPLETE", conditionMessage(e))) "incomplete" else "error")
  # View(x) as in RStudio: the data is kept here under its title, and the page told to show it (takeViews)
  views <- list()
  asked <- character(0)
  view <- function(x, title) {
    if (missing(title)) title <- paste(deparse(substitute(x), nlines = 1L), collapse = " ")
    if (is.matrix(x) || is.list(x) && !is.data.frame(x)) x <- tryCatch(as.data.frame(x), error = function(e) data.frame(value = I(list(x))))
    if (!is.data.frame(x)) x <- data.frame(value = x)
    v <- .cab$views; v[[title]] <- x; .cab$views <- v
    .cab$asked <- unique(c(.cab$asked, title))
    invisible(NULL)
  }
  takeViews <- function() { a <- .cab$asked; .cab$asked <- character(0); paste0("[", paste(q(a), collapse = ","), "]") }
  # str() of an object, as text
  str_ <- function(name) paste(utils::capture.output(utils::str(get(name, envir = globalenv()))), collapse = "\n")
  # the files in the working directory
  files <- function() {
    f <- list.files(all.files = FALSE, recursive = TRUE)
    i <- file.info(f)
    # (webR's own leftovers: an empty Rplots.pdf from its graphics device, the WebAssembly build's profiling file)
    keep <- !(f == "default.profraw" | (f == "Rplots.pdf" & !is.na(i$size) & i$size == 0))
    f <- f[keep]; i <- i[keep, , drop = FALSE]
    if (!length(f)) return("[]")
    paste0("[", paste0("{\"name\":", q(f), ",\"size\":", ifelse(is.na(i$size), 0, i$size), "}", collapse = ","), "]")
  }
  # the packages: installed (with their titles; "base": R's own – those with a priority, base or recommended, as webR
  # installs others into R's own library too), and attached
  ownPkgs <- c("webr", "translations")  # (webR's and R's own, without a priority)
  packages <- function() {
    ip <- utils::installed.packages(fields = "Title")
    att <- sub("^package:", "", grep("^package:", search(), value = TRUE))
    title <- ifelse(is.na(ip[, "Title"]), "", gsub("\\s+", " ", ip[, "Title"]))
    paste0("[", paste0("{\"name\":", q(ip[, "Package"]), ",\"version\":", q(ip[, "Version"]), ",\"title\":", q(title),
      ",\"base\":", ifelse(is.na(ip[, "Priority"]) & !(ip[, "Package"] %in% .cab$ownPkgs), "false", "true"),
      ",\"attached\":", ifelse(ip[, "Package"] %in% att, "true", "false"), "}", collapse = ","), "]")
  }
  # the packages webR's repository has (names and versions)
  available <- function() {
    a <- utils::available.packages(contriburl = utils::contrib.url(getOption("webr_pkg_repos")[1], "binary"))
    paste0("[", paste0("[", q(a[, "Package"]), ",", q(a[, "Version"]), "]", collapse = ","), "]")
  }

  # ---- help: ?topic, help(), help(package =) and ??pattern show in the page's Help tab (takeHelp), not as text
  helpAsked <- list()
  askHelp <- function(h) { v <- .cab$helpAsked; v[[length(v) + 1L]] <- h; .cab$helpAsked <- v }
  takeHelp <- function() {
    a <- .cab$helpAsked; .cab$helpAsked <- list()
    if (!length(a)) return("[]")
    paste0("[", paste(vapply(a, function(h) paste0("{", paste0(q(names(h)), ":", q(unlist(h)), collapse = ","), "}"), ""), collapse = ","), "]")
  }
  showHelp <- function(x, ...) {
    paths <- as.character(x)
    topic <- attr(x, "topic")
    if (!length(paths)) {
      cat("No documentation for ", sQuote(topic), " in the packages installed – try ??", topic, "\n", sep = "")
    } else {
      p <- paths[1L]
      .cab$askHelp(list(topic = basename(p), package = basename(dirname(dirname(p)))))
      if (length(paths) > 1L) cat("Help on ", sQuote(topic), " is in several packages: ", paste(basename(dirname(dirname(paths))), collapse = ", "), " – showing ", basename(dirname(dirname(p))), "\n", sep = "")
    }
    invisible(x)
  }
  # a help page's file in a package, from one of its topics (an alias)
  helpFile <- function(topic, pkg) {
    if (nzchar(pkg) && nzchar(system.file(package = pkg))) {
      a <- suppressWarnings(tryCatch(readRDS(file.path(find.package(pkg), "help", "aliases.rds")), error = function(e) NULL))
      if (!is.null(a) && !is.na(a[topic])) return(c(pkg, a[[topic]]))
    }
    h <- as.character(do.call(utils::help, list(topic, try.all.packages = TRUE)))
    if (!length(h)) return(NULL)
    c(basename(dirname(dirname(h[1L]))), basename(h[1L]))
  }
  # a help page as HTML (R's own Rd2HTML); its links read ../../package/help/topic
  helpPage <- function(topic, pkg = "") {
    f <- helpFile(topic, pkg)
    if (is.null(f)) stop("No documentation for ", sQuote(topic), " in the packages installed")
    rd <- utils:::.getHelpFile(file.path(find.package(f[1L]), "help", f[2L]))
    out <- tempfile(fileext = ".html")
    on.exit(unlink(out))
    tools::Rd2HTML(rd, out = out, package = f[1L], dynamic = TRUE)
    html <- paste(readLines(out, warn = FALSE, encoding = "UTF-8"), collapse = "\n")
    paste0("{\"package\":", q(f[1L]), ",\"file\":", q(f[2L]), ",\"topic\":", q(topic), ",\"html\":", q(html), "}")
  }
  # a package's help pages (name, title, first topic)
  helpIndex <- function(pkg) {
    m <- readRDS(file.path(find.package(pkg), "Meta", "Rd.rds"))
    d <- utils::packageDescription(pkg)
    m <- m[order(tolower(m$Name)), , drop = FALSE]
    rows <- if (nrow(m)) paste0("{\"name\":", q(m$Name), ",\"title\":", q(gsub("\\s+", " ", m$Title)), ",\"topic\":", q(vapply(m$Aliases, function(a) a[1L], "")), "}") else character(0)
    paste0("{\"package\":", q(pkg), ",\"title\":", q(if (is.null(d$Title)) "" else gsub("\\s+", " ", d$Title)), ",\"version\":", q(if (is.null(d$Version)) "" else d$Version),
      ",\"topics\":[", paste(rows, collapse = ","), "]}")
  }
  # every help topic of the packages installed (made again when packages are added)
  rdKey <- ""
  rdIndex <- function() {
    pk <- sort(rownames(utils::installed.packages()))
    key <- paste(pk, collapse = ",")
    if (identical(.cab$rdKey, key)) return(.cab$rdIdx)
    parts <- lapply(pk, function(p) {
      m <- suppressWarnings(tryCatch(readRDS(file.path(find.package(p), "Meta", "Rd.rds")), error = function(e) NULL))
      if (is.null(m) || !nrow(m)) return(NULL)
      n <- lengths(m$Aliases)
      data.frame(package = p, alias = unlist(m$Aliases), title = rep(gsub("\\s+", " ", m$Title), n), name = rep(m$Name, n), stringsAsFactors = FALSE)
    })
    idx <- do.call(rbind, parts)
    .cab$rdKey <- key; .cab$rdIdx <- idx
    idx
  }
  # help pages for words: a topic named so first, then topics starting with them, containing them, then titles with
  # every word in them
  helpSearch <- function(pattern, n = 60) {
    idx <- rdIndex(); p <- tolower(trimws(pattern))
    if (!nzchar(p) || is.null(idx)) return("[]")
    a <- tolower(idx$alias); t <- tolower(idx$title)
    words <- strsplit(p, "[[:space:]]+")[[1L]]
    inTitle <- Reduce(`&`, lapply(words, function(w) grepl(w, t, fixed = TRUE)))
    score <- ifelse(a == p, 0, ifelse(startsWith(a, p), 1, ifelse(grepl(p, a, fixed = TRUE), 2, ifelse(inTitle, 3, NA))))
    keep <- which(!is.na(score))
    keep <- keep[order(score[keep], nchar(idx$alias[keep]), idx$alias[keep])]
    keep <- head(keep[!duplicated(paste(idx$package[keep], idx$name[keep]))], n)
    if (!length(keep)) return("[]")
    paste0("[", paste0("{\"topic\":", q(idx$alias[keep]), ",\"package\":", q(idx$package[keep]), ",\"title\":", q(idx$title[keep]), "}", collapse = ","), "]")
  }

  # ---- completion, as R's own console does it (utils' rcompgen): the word being typed and what it can become
  complete <- function(line, pos) {
    utils:::.assignLinebuffer(line)
    utils:::.assignEnd(pos)
    tok <- utils:::.guessTokenFromLine()
    utils:::.completeToken()
    co <- head(utils:::.retrieveCompletions(), 300)
    if (!length(co)) return(paste0("{\"token\":", q(tok), ",\"items\":[]}"))
    kind <- vapply(co, function(x) {
      if (endsWith(x, "=")) return("arg")
      if (grepl("[$@]", x)) return("field")
      o <- tryCatch(get(x, envir = globalenv()), error = function(e) NULL)
      if (is.function(o)) "function" else if (is.data.frame(o)) "data" else if (is.null(o)) "other" else "value"
    }, "", USE.NAMES = FALSE)
    paste0("{\"token\":", q(tok), ",\"items\":[", paste0("{\"label\":", q(co), ",\"kind\":", q(kind), "}", collapse = ","), "]}")
  }
  # a function's arguments, as its usage reads: mean(x, ...)
  signature <- function(name) {
    f <- tryCatch(get(name, envir = globalenv(), mode = "function"), error = function(e) NULL)
    if (is.null(f)) return("")
    a <- args(f)
    if (is.null(a)) return("")
    s <- paste(trimws(deparse(a, width.cutoff = 500L)), collapse = " ")
    sub("^function ?", name, sub("\\s*NULL\\s*$", "", s))
  }

  # ---- the workspace: the objects saved to a file (and the packages they need), and loaded again
  saveWorkspace <- function(path) {
    save(list = ls(globalenv(), all.names = TRUE), envir = globalenv(), file = path)
    ip <- utils::installed.packages()
    own <- setdiff(ip[is.na(ip[, "Priority"]), "Package"], .cab$ownPkgs)
    need <- intersect(own, loadedNamespaces())
    paste0("{\"size\":", file.size(path), ",\"packages\":[", paste(q(need), collapse = ","), "]}")
  }
  loadWorkspace <- function(path) { n <- load(path, envir = globalenv()); sum(!startsWith(n, ".")) }
}, envir = .cab)
# help shown in the page rather than as text (help(), ?, help(package =)), and ??pattern searched there
registerS3method("print", "help_files_with_topic", .cab$showHelp, envir = asNamespace("utils"))
registerS3method("print", "packageInfo", function(x, ...) { .cab$askHelp(list(package = x$name)); invisible(x) }, envir = asNamespace("utils"))
utils::rc.settings(ipck = TRUE)
# View() for the code people write, and ??pattern searching the help in the page (attached, so they aren't objects
# of theirs; ? otherwise as R's own)
attach(list(
  View = function(x, title) if (missing(title)) .cab$view(x, paste(deparse(substitute(x), nlines = 1L), collapse = " ")) else .cab$view(x, title),
  `?` = function(e1, e2) {
    ex <- substitute(e1)
    if (missing(e2) && is.call(ex) && identical(ex[[1L]], as.name("?"))) {
      w <- ex[[2L]]
      .cab$askHelp(list(search = if (is.character(w)) w else paste(deparse(w), collapse = " ")))
      return(invisible(NULL))
    }
    mc <- sys.call()
    mc[[1L]] <- quote(utils::`?`)
    eval(mc, parent.frame())
  }
), name = "caboodle:tools", warn.conflicts = FALSE)
