# ----------------------------------------------------------
# install_ciblab(): install source package from ciblab on all OS
# - Always installs .tar.gz source (no local auto-detect, no binaries)
# - Uses CRAN + Bioconductor repos
# - Temporarily sets options(timeout = 9999) and restores it on exit
# - Downloads the source first with visible progress, then installs locally
# - On failure: prints OS-specific build-tool guidance and likely causes
# - Status messages: "Installation completed." / "Installation interrupted."
# ----------------------------------------------------------

install_ciblab <- function(
  pkg        = "phyloR",                          # package name
  version    = "0.1.0",                           # version; must be provided
  base_url   = "https://www.ciblab.net/pub/pkg",  # remote base URL
  upgrade    = "never",                           # remotes upgrade policy
  deps       = c("Depends", "Imports"),           # dependency classes (hard deps only)
  verbose    = TRUE,                              # print progress
  download_method = NULL                          # optional utils::download.file() method
) {
  # 0) Extend network timeout; restore on exit
  old_timeout <- getOption("timeout")
  options(timeout = 9999)
  on.exit(options(timeout = old_timeout), add = TRUE)

  # 1) Ensure CRAN + Bioconductor repos and remotes availability
  if (!requireNamespace("BiocManager", quietly = TRUE)) {
    install.packages("BiocManager", repos = "https://cloud.r-project.org")
  }
  options(repos = BiocManager::repositories())

  if (!requireNamespace("remotes", quietly = TRUE)) {
    install.packages("remotes")
  }

  # 2) Version required
  if (is.null(version)) {
    message("Status: Installation interrupted.")
    stop("Please provide 'version' (e.g., '0.1.0'). Local file install and auto-detect are removed.")
  }

  # 3) Build the source URL and download with visible progress
  file_src <- sprintf("%s/%s_%s.tar.gz", base_url, pkg, version)
  tf <- tempfile(fileext = ".tar.gz")

  if (verbose) {
    message("Downloading source package ...")
    message(sprintf("  Package : %s", pkg))
    message(sprintf("  Version : %s", version))
    message(sprintf("  URL     : %s", file_src))
  }

  dl_ok <- try({
    if (is.null(download_method)) {
      utils::download.file(file_src, tf, mode = "wb", quiet = FALSE)
    } else {
      utils::download.file(file_src, tf, mode = "wb", quiet = FALSE, method = download_method)
    }
  }, silent = TRUE)

  # 3a) Detect download failures or empty file
  if (inherits(dl_ok, "try-error") ||
      !file.exists(tf) ||
      isTRUE(tryCatch(file.info(tf)$size, error = function(e) 0L) <= 0L)) {

    message("Status: Installation interrupted.")
    .print_likely_causes(stage = "download", url = file_src)
    stop(sprintf("Failed to download %s %s.\nError summary:\n%s",
                 pkg, version, as.character(dl_ok)))
  }

  if (verbose) message("Download complete: ", tf)

  # 4) Install from the downloaded local source tarball
  res <- try(
    remotes::install_local(
      path         = tf,
      dependencies = deps,
      upgrade      = upgrade
    ),
    silent = TRUE
  )

  if (!inherits(res, "try-error")) {
    if (verbose) {
      message("Installation finished. Try: library(", pkg, ")")
      message("Status: Installation completed.")
    }
    return(invisible(TRUE))
  }

  # 5) On failure: print guidance and likely causes, then stop
  .print_build_guide(err = res, src_url = file_src, pkg = pkg, deps = deps)
  .print_likely_causes(stage = "build", url = file_src)
  message("Status: Installation interrupted.")
  stop(sprintf("Failed to install %s %s from source.\nError summary:\n%s",
               pkg, version, as.character(res)))
}

# ===== helper: print OS-specific build-tool instructions on failure =====
.print_build_guide <- function(err, src_url, pkg, deps) {
  os  <- Sys.info()[["sysname"]]
  rv  <- getRversion()

  cat("\nSource installation failed for package '", pkg, "'.\n", sep = "")
  cat("Error summary:\n", as.character(err), "\n\n", sep = "")

  if (os == "Windows") {
    rtools <- if (rv < "4.2.0") "Rtools40"
    else if (rv < "4.3.0") "rtools42"
    else if (rv < "4.4.0") "rtools43"
    else "rtools44"

    cat("[Windows] Install the matching Rtools for your R version:\n",
        "  ", rtools, " -> https://cran.r-project.org/bin/windows/Rtools/\n",
        "Then restart R.\n", sep = "")
    if (rtools == "Rtools40") {
      cat("If needed, add Rtools40 to PATH via ~/.Renviron and restart R:\n",
          '  RTOOLS40_HOME="C:\\\\rtools40"\n',
          '  PATH="${RTOOLS40_HOME}\\\\usr\\\\bin;${RTOOLS40_HOME}\\\\mingw64\\\\bin;${PATH}"\n', sep = "")
    } else {
      cat("Note: rtools42/43/44 usually configure PATH automatically.\n")
    }
    cat("Self-check in R:\n",
        "  if (!requireNamespace('pkgbuild', quietly = TRUE)) install.packages('pkgbuild')\n",
        "  pkgbuild::has_build_tools(debug = TRUE)\n",
        "  Sys.which(c('make','gcc','g++'))\n\n", sep = "")
  } else if (os == "Darwin") {
    cat("[macOS] Prepare build tools:\n",
        "  1) Xcode Command Line Tools:  xcode-select --install\n",
        "  2) Fortran compiler:\n",
        "     - Homebrew:  brew install gcc\n",
        "     - Or download a matching gfortran from CRAN macOS tools page\n",
        "Self-check:\n",
        "  system('clang --version'); system('gfortran --version')\n\n", sep = "")
  } else {
    os_release <- "/etc/os-release"
    id <- if (file.exists(os_release)) {
      ln <- readLines(os_release, warn = FALSE)
      sub('^ID="?([^"]+)"?$', '\\1', ln[grepl("^ID=", ln)][1])
    } else NA_character_

    if (isTRUE(id %in% c("ubuntu","debian","linuxmint","pop"))) {
      cat("[Linux / Debian or Ubuntu family]\n",
          "sudo apt update\n",
          "sudo apt install -y r-base-dev build-essential gfortran \n",
          "    libcurl4-openssl-dev libssl-dev libxml2-dev libxt-dev \n",
          "    libjpeg-dev libpng-dev libtiff5-dev libicu-dev zlib1g-dev\n\n", sep = "")
    } else if (isTRUE(id %in% c("centos","rhel","rocky","almalinux","fedora"))) {
      cat("[Linux / RHEL, CentOS, Fedora family]\n",
          'sudo yum groupinstall -y "Development Tools"\n',
          "sudo yum install -y R-devel gcc gcc-c++ gcc-gfortran \n",
          "    libcurl-devel openssl-devel libxml2-devel xz-devel zlib-devel libXt-devel \n",
          "    libjpeg-turbo-devel libpng-devel libtiff-devel\n",
          "# Or with dnf on newer systems:\n",
          'sudo dnf groupinstall -y "Development Tools"\n',
          "sudo dnf install -y R-devel gcc gcc-c++ gcc-gfortran \n",
          "    libcurl-devel openssl-devel libxml2-devel xz-devel zlib-devel libXt-devel \n",
          "    libjpeg-turbo-devel libpng-devel libtiff-devel\n\n", sep = "")
    } else if (isTRUE(id %in% c("opensuse-leap","opensuse-tumbleweed","sles"))) {
      cat("[Linux / openSUSE or SLES]\n",
          "sudo zypper install -y -t pattern devel_C_C++\n",
          "sudo zypper install -y gcc-fortran libcurl-devel libopenssl-devel \n",
          "    libxml2-devel xz-devel libXt-devel libjpeg62-devel libpng16-devel libtiff-devel\n\n", sep = "")
    } else {
      cat("[Linux (generic)] Ensure you have: gcc, g++, gfortran, make, and common headers\n",
          "  (curl, openssl, xml2, xz, Xt, jpeg, png, tiff, icu, zlib, etc.).\n\n", sep = "")
    }
    cat("Self-check:\n",
        "  R CMD config CC ; R CMD config CXX ; R CMD config FC\n",
        "  if (!requireNamespace('pkgbuild', quietly = TRUE)) install.packages('pkgbuild')\n",
        "  pkgbuild::has_build_tools(debug = TRUE)\n\n", sep = "")
  }

  cat("After preparing the build toolchain, retry installation:\n",
      '  remotes::install_url("', src_url, '", ',
      'dependencies = c("', paste(deps, collapse = '","'), '"), upgrade = "never")\n\n', sep = "")
}

# ===== helper: print likely causes depending on stage (ASCII only) =====
.print_likely_causes <- function(stage = c("download","build"), url = NULL) {
  stage <- match.arg(stage)
  if (stage == "download") {
    cat("\nLikely causes (download stage):\n",
        "  - Network connectivity or timeout issues\n",
        "  - Proxy or firewall blocking the URL\n",
        "  - Incorrect or unavailable URL: ", if (is.null(url)) "(unknown)" else url, "\n",
        "  - TLS/SSL certificate problems on this machine\n",
        "  - Temporary server outage; try again later\n\n", sep = "")
  } else {
    cat("\nLikely causes (build or installation stage):\n",
        "  - Missing C/C++/Fortran toolchain for your OS\n",
        "  - Missing system headers (curl, openssl, xml2, xz, Xt, jpeg, png, tiff, icu, zlib, etc.)\n",
        "  - Permission denied when writing to the target library path\n",
        "  - Conflicting packages already loaded; restart R and retry\n",
        "  - Windows DLL locks (restart R or reboot)\n",
        "  - Disk space limits or antivirus interference\n\n", sep = "")
  }
}
