# inst/tinytest/test_download.R
#
# Non-network tests for the CBLIB download helpers.

Sys.setenv(ROI_LOAD_PLUGINS = "FALSE")
library(ROI.format.cbf)

sample_index <- c(
    '<html><body>',
    '<a href="beam7.cbf.gz">beam7.cbf.gz</a>',
    '<a href="nested/beam30.cbf.gz">beam30.cbf.gz</a>',
    '<a href="beam7.cbf.gz">duplicate</a>',
    '</body></html>'
)

expect_equal(
    ROI.format.cbf:::.cblib_extract_instance_names(sample_index),
    c("beam30.cbf.gz", "beam7.cbf.gz"),
    info = "Index parser extracts unique .cbf.gz links"
)

expect_equal(
    ROI.format.cbf:::.cblib_normalize_instance_name("beam7"),
    "beam7.cbf.gz",
    info = "Bare instance names gain the .cbf.gz suffix"
)

expect_equal(
    ROI.format.cbf:::.cblib_normalize_instance_name("beam7.cbf"),
    "beam7.cbf.gz",
    info = "Plain .cbf names are normalized to the archive name"
)

expect_equal(
    ROI.format.cbf:::.cblib_normalize_instance_name("beam7.cbf.gz"),
    "beam7.cbf.gz",
    info = "Archive names are left unchanged"
)

src_dir <- tempfile("cblib-src-")
out_dir <- tempfile("cblib-out-")
dir.create(src_dir)
dir.create(out_dir)

src_gz <- file.path(src_dir, "toy.cbf.gz")
con <- gzfile(src_gz, open = "wb")
writeLines(c("VER", "4"), con)
close(con)

out_cbf <- file.path(out_dir, "toy.cbf")
ROI.format.cbf:::.cblib_gunzip(src_gz, out_cbf, overwrite = TRUE)

expect_equal(
    readLines(out_cbf, warn = FALSE),
    c("VER", "4"),
    info = "Internal gunzip helper restores the original CBF text"
)
