#!/usr/bin/env Rscript --no-save --no-restore

# Make sure python is properly configured
if( get0("check_rpymat", inherits = TRUE, ifnotfound = TRUE) ) {
  if(system.file(package = "ravemanager") == "") {
    lib_path <- Sys.getenv("RAVE_LIB_PATH", unset = Sys.getenv("R_LIBS_USER", unset = .libPaths()[[1]]))
    do.call(
      "install.packages",
      list(pkgs = 'ravemanager', repos = 'https://beauchamplab.r-universe.dev', lib = lib_path)
    )
  }
  ravemanager <- asNamespace("ravemanager")
  ravemanager$configure_python(verbose = TRUE)

}

work_path <- normalizePath("{{ work_path }}", winslash = "/")
ct_path0 <- normalizePath("{{ ct_path }}", mustWork = TRUE, winslash = "/")
mri_path0 <- normalizePath("{{ mri_path }}", mustWork = TRUE, winslash = "/")
clean_source <- as.logical("{{ clean_source }}")
inverse_target <- as.logical("{{ inverse_target }}")
precenter_source <- as.logical("{{ precenter_source }}")
reg_type <- "{{ reg_type }}"
interp <- "{{ interp }}"
similarity <- "{{ similarity }}"
optimizer <- "{{ optimizer }}"

coreg_path <- file.path(work_path, "coregistration")
if(!dir.exists(coreg_path)) { raveio::dir_create2(coreg_path) }

deriv_path <- file.path(work_path, "derivative")
if(!dir.exists(deriv_path)) { raveio::dir_create2(deriv_path) }

ct_ext <- ifelse(grepl("\\.gz$", x = ct_path0, ignore.case = TRUE), ".nii.gz", ".nii")
ct_path <- file.path(coreg_path, sprintf("CT_RAW%s", ct_ext))
file.copy(ct_path0, ct_path, overwrite = TRUE, recursive = FALSE, copy.mode = TRUE, copy.date = TRUE)
file.copy(ct_path0, file.path(deriv_path, sprintf("CT_RAW%s", ct_ext)), overwrite = TRUE, recursive = FALSE, copy.mode = TRUE, copy.date = TRUE)

mri_ext <- ifelse(grepl("\\.gz$", x = mri_path0, ignore.case = TRUE), ".nii.gz", ".nii")
mri_path <- file.path(coreg_path, sprintf("MRI_reference%s", mri_ext))
file.copy(mri_path0, mri_path, overwrite = TRUE, recursive = FALSE, copy.mode = TRUE, copy.date = TRUE)



# Write down configuration files
raveio::save_yaml(
  file = file.path(deriv_path, "conf-coregistration.yaml"),
  list(
    `Heads up` = "Do NOT edit this file",
    profile = "CT coregister to MRI",
    work_path = work_path,
    timestamp = strftime(Sys.time(), "%a %b %d %H:%M:%S %Z %Y", tz = "UTC"),
    command = list(
      comment = "This is R function call",
      execute = "raveio::py_nipy_coreg",
      arguments = list(
        clean_source = clean_source,
        inverse_target = inverse_target,
        precenter_source = precenter_source,
        reg_type = reg_type,
        interp = interp,
        similarity = similarity,
        optimizer = optimizer
      )
    ),
    input_image = list(
      type = "nifti",
      path = ct_path0,
      backup = c(
        sprintf("./derivative/CT_RAW%s", ct_ext),
        sprintf("./coregistration/CT_RAW%s", ct_ext)
      ),
      comment = "original CT image file"
    ),
    reference_image = list(
      type = "nifti",
      path = mri_path0,
      backup = c(
        sprintf("./coregistration/MRI_reference%s", mri_ext)
      ),
      comment = "Reference MR image file, the CT is aligned to this reference image"
    ),
    outputs = list(
      "CT_IJK_to_MR_RAS" = list(
        type = "transform",
        dimension = "4x4",
        path = "./coregistration/CT_IJK_to_MR_RAS.txt",
        backup = "./coregistration/transform-ctIJK2mrRAS.txt",
        transform_from = list(
          volume = "input_image",
          coordinate_system = "IJK"
        ),
        transform_to = list(
          volume = "reference_image",
          space = "scanner",
          coordinate_system = "RAS"
        ),
        comment = "From voxel IJK coordinate to MRI scanner RAS coordinate"
      ),

      "CT_RAS_to_MR_RAS" = list(
        type = "transform",
        dimension = "4x4",
        path = "./coregistration/CT_RAS_to_MR_RAS.txt",
        backup = "./coregistration/transform-ctRAS2mrRAS.txt",
        transform_from = list(
          volume = "input_image",
          space = "scanner (CT)",
          coordinate_system = "RAS"
        ),
        transform_to = list(
          volume = "reference_image",
          space = "scanner",
          coordinate_system = "RAS"
        ),
        comment = "From CT scanner RAS coordinate to MRI scanner RAS coordinate"
      ),

      ct_in_t1 = list(
        type = "nifti",
        path = "./coregistration/ct_in_t1.nii",
        backup = "./derivative/ct_in_t1.nii",
        comment = "re-sampled CT; the resolution is the same as reference MRI"
      )
    )
  )
)


raveio::py_nipy_coreg(
  ct_path = ct_path,
  mri_path = mri_path,
  clean_source = clean_source,
  inverse_target = inverse_target,
  precenter_source = precenter_source,
  reg_type = reg_type,
  interp = interp,
  similarity = similarity,
  optimizer = optimizer
)

# Finalize
file.copy(
  from = file.path(coreg_path, "ct_in_t1.nii"),
  to = file.path(deriv_path, "ct_in_t1.nii"),
  overwrite = TRUE,
  recursive = FALSE,
  copy.mode = TRUE,
  copy.date = TRUE
)


file.copy(
  from = file.path(coreg_path, "CT_IJK_to_MR_RAS.txt"),
  to = file.path(deriv_path, "transform-ctIJK2mrRAS.txt"),
  overwrite = TRUE,
  recursive = FALSE,
  copy.mode = TRUE,
  copy.date = TRUE
)

file.copy(
  from = file.path(coreg_path, "CT_RAS_to_MR_RAS.txt"),
  to = file.path(deriv_path, "transform-ctRAS2mrRAS.txt"),
  overwrite = TRUE,
  recursive = FALSE,
  copy.mode = TRUE,
  copy.date = TRUE
)

## END OF RAVE Script: CT MR coregistration via nipy
