#!/usr/bin/env Rscript

# Load the package
library(VIProDesign)
if (!requireNamespace("optparse", quietly = TRUE)) {
  stop("The 'optparse' package is required to run this script. Please install it using install.packages('optparse').")
}
library(optparse)

option_list <- list(
  make_option(c("-p", "--predifined_cluster_number"), type="numeric", default=NULL, help="Predefined cluster number", metavar="numeric"),
  make_option(c("-m", "--max_cluster_number"), type="numeric", default=NULL, help="Maximum cluster number", metavar="numeric"),
  make_option(c("-o", "--output_prefix"), type="character", default="OUTPUT", help="Output prefix", metavar="character"),
  make_option(c("-f", "--file"), type="character", default=NULL, help="Input FASTA file", metavar="character"),
  make_option(c("-r", "--use_cd_hit"), type="logical", default=TRUE, help="Remove redundancy with cd-hit [default %default]", metavar="logical"),
  make_option(c("-c", "--cd_hit_path"), type = "character", default = "cd-hit",help = "Path to the cd-hit executable [default %default]", metavar = "character"),
  make_option(c("-t", "--cutoff"), type="numeric", default=0.99, help="Cutoff for cd-hit [default %default]", metavar="numeric"),
  make_option(c("-x", "--remove_outliers"), type="logical", default=TRUE, help="Remove outliers [default %default]", metavar="logical")
  make_option(c("-d", "--output_dir"), type = "character", default = getwd(),help = "Directory for output files [default: current working directory]", metavar = "character")
  )

opt_parser <- OptionParser(option_list=option_list)
opt <- parse_args(opt_parser)
output_prefix <- file.path(opt$output_dir, opt$output_prefix)
# Validate arguments
if (is.null(opt$file) || is.null(opt$output_prefix)) {
  print_help(opt_parser)
  stop("Input FASTA file and output prefix are required.", call. = FALSE)
}

if (!is.null(opt$predifined_cluster_number) && !is.null(opt$max_cluster_number)) {
  stop("Specify either predefined cluster number or maximum cluster number, not both.", call. = FALSE)
}

if (is.null(opt$predifined_cluster_number) && is.null(opt$max_cluster_number)) {
  stop("Specify either predefined cluster number or maximum cluster number.", call. = FALSE)
}


# Run the main function
VIProDesignPackage::run_VIProDesign(
  file = opt$file,
  output_prefix = opt$output_prefix,
  max_cluster_number = opt$max_cluster_number,
  predefined_cluster_number = opt$predifined_cluster_number,
  use_cd_hit = opt$use_cd_hit,
  cd_hit_path = opt$cd_hit_path,
  cutoff = opt$cutoff,
  remove_outliers = opt$remove_outliers
)
