# setup tinytest for checkmate functionality
library("tinytest")
library("checkmate")
using("checkmate")

has_deps_text <- requireNamespace("pdftools", quietly = TRUE) &&
  requireNamespace("tesseract", quietly = TRUE) &&
  requireNamespace("callr", quietly = TRUE)

has_deps_image <- requireNamespace("pdftools", quietly = TRUE) &&
  requireNamespace("magick", quietly = TRUE) &&
  requireNamespace("callr", quietly = TRUE)

pdf <- system.file("extdata", "test.pdf", package = "inlpubs")

# ------ get_pdf_text ------

if (has_deps_text) {
  # returns the output path invisibly
  out <- get_pdf_text(pdf)
  expect_true(is.character(out))

  # output file exists and has a .txt extension
  expect_true(file.exists(out))
  expect_true(grepl("\\.txt$", out, ignore.case = TRUE))

  # file contains non-empty text
  txt <- readLines(out, warn = FALSE)
  expect_true(length(txt) > 0L)
  expect_true(any(nzchar(txt)))

  # text is ASCII only (no non-ASCII characters after normalization)
  expect_true(all(txt == iconv(txt, "UTF-8", "ASCII", sub = "?")))

  # custom output path is respected
  custom <- tempfile(fileext = ".txt")
  get_pdf_text(pdf, output = custom)
  expect_true(file.exists(custom))

  # path without .txt extension gets .txt appended
  no_ext <- tempfile()
  result <- get_pdf_text(pdf, output = no_ext)
  expect_true(grepl("\\.txt$", result, ignore.case = TRUE))

  # invalid input raises an error
  expect_error(get_pdf_text("nonexistent.pdf"))

  # invalid dpi raises an error
  expect_error(get_pdf_text(pdf, dpi = 50L))
  expect_error(get_pdf_text(pdf, dpi = 2000L))

  unlink(c(out, custom, result))
}

# ------ get_pdf_image ------

if (has_deps_image) {
  # returns the output path invisibly
  img <- get_pdf_image(pdf)
  expect_true(is.character(img))

  # output file exists and has a .jpg extension
  expect_true(file.exists(img))
  expect_true(grepl("\\.jpg$", img, ignore.case = TRUE))

  # file is a non-trivially sized JPEG (at least 1 KB)
  expect_true(file.size(img) > 1024L)

  # custom output path is respected
  custom_img <- tempfile(fileext = ".jpg")
  get_pdf_image(pdf, output = custom_img)
  expect_true(file.exists(custom_img))

  # path without .jpg extension gets .jpg appended
  no_ext_img <- tempfile()
  result_img <- get_pdf_image(pdf, output = no_ext_img)
  expect_true(grepl("\\.jpg$", result_img, ignore.case = TRUE))

  # larger width produces a larger file
  img_small <- get_pdf_image(pdf, width = 100L)
  img_large <- get_pdf_image(pdf, width = 500L)
  expect_true(file.size(img_large) > file.size(img_small))

  # invalid input raises an error
  expect_error(get_pdf_image("nonexistent.pdf"))

  # invalid page raises an error
  expect_error(get_pdf_image(pdf, page = 0L))

  # invalid width raises an error
  expect_error(get_pdf_image(pdf, width = 0L))

  unlink(c(img, custom_img, result_img, img_small, img_large))
}
