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

# Make sure python is properly configured if ravemanager is installed
# or do nothing
if( get0("check_rpymat", inherits = TRUE, ifnotfound = TRUE) ) {
  # This is non-CRAN package for RAVE users,
  # For normal CRAN users, this script will end up with errors unless
  # they explicitly configure python environments
  if(system.file(package = "ravemanager") != "") {
    ravemanager <- asNamespace("ravemanager")
    ravemanager$configure_python(verbose = TRUE)
  }
  if(system.file(package = "rpymat") != "") {
    rpymat <- asNamespace("rpymat")
    existing_pkgs <- rpymat$list_pkgs()
    if(!isTRUE("nipy" %in% existing_pkgs$package)) {
      # try to configure nipy to RAVE isolated envrionment
      rpymat$add_packages("nipy", pip = 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)) { dir.create(coreg_path, showWarnings = FALSE, recursive = TRUE) }

deriv_path <- file.path(work_path, "derivative")
if(!dir.exists(deriv_path)) { dir.create(deriv_path, showWarnings = FALSE, recursive = TRUE) }

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
ieegio::io_write_yaml(
  con = 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 = "ravecore::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"
      )
    )
  )
)


ravecore::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
