#!/bin/bash

mkdir logs
scratch_dir=$(echo $PWD | sed "s/\/data\/ucct\/bi\/scratch_tmp/\/scratch/g")

if test -f nextclade_combined.csv; then rm nextclade_combined.csv; fi
if test -d A_H1; then rm -rf A_H1; fi
if test -d A_H3; then rm -rf A_H3; fi
if test -d B; then rm -rf B; fi

# Auxiliary file in which a nextclade dataset is associated with a specific flu subtype.
AUX_FILE="equivalences.txt"

# Log file for nextclade version check
logfile=$(echo "$PWD/nextclade.log")
timestamp=$(date +"%Y-%m-%d_%H-%M-%S")
log_message() {
    local message="$1"
    case "$2" in
        "bold")
            echo -e "\e[1;37m$message\e[0m"
            echo -e "$timestamp - \e[1;37m$message\e[0m" >> $logfile
            ;;
        "red")
            echo -e "\e[31m$message\e[0m"
            echo -e "$timestamp - \e[31m$message\e[0m" >> $logfile
            ;;
        "green")
            echo -e "\e[32m$message\e[0m"
            echo -e "$timestamp - \e[32m$message\e[0m" >> $logfile
            ;;
        "blk_red")
            echo -e "\e[1;5;97;5;41m$message\e[0m"
            echo -e "$timestamp - \e[1;5;97;5;41m$message\e[0m" >> $logfile
            ;;
        *)
            echo -e "$message"
            echo -e "$timestamp - $message" >> $logfile
            ;;
    esac
}

# Nextclade version check
update_nextclade() {
    echo
    log_message "Starting NEXTCLADE check/update." bold
    log_message "Checking Nextclade container version..."
    url=$(curl -s "https://depot.galaxyproject.org/singularity/")
    latest_version_nextclade=$(echo "$url" | grep -oP 'nextclade:[^"]+' | sort -V | tail -n 1 | awk -F'>' '{print $1}' | sed 's/<\/a//')
    log_message "Latest version available of Nextclade:\e[1;38;5;220m $latest_version_nextclade" bold

    log_message "Checking if latest version of Nextclade image is already downloaded..."
    if [ -e "/data/ucct/bi/pipelines/singularity-images/$latest_version_nextclade" ]; then
        log_message "File $latest_version_nextclade already downloaded."
        log_message "Nextclade container is UP TO DATE. \xE2\x9C\x85"
    else
        log_message "Downloading $latest_version_nextclade file..."
        wget -P "/data/ucct/bi/pipelines/singularity-images" "https://depot.galaxyproject.org/singularity/$latest_version_nextclade"
        if [ $? -eq 0 ]; then
            log_message "$latest_version_nextclade file succesfully downloaded." green
        else
            log_message "An error occurred during file downloading." blk_red
        fi
    fi
}
update_nextclade

echo "
  while read -r nextclade_dataset subtype_folder; do
      folder_path=\"../04-irma/\$subtype_folder\"
      if [ -d \"\$folder_path\" ]; then
          if [[ \"\$subtype_folder\" == \"A_H1\" || \"\$subtype_folder\" == \"A_H3\" ]]; then
              input_file=\"\$folder_path/A_HA.txt\"
          elif [[ \"\$subtype_folder\" == \"B\" ]]; then
              input_file=\"\$folder_path/B_HA.txt\"
          else
              echo \"Unknown folder: \$subtype_folder\"
              continue
          fi

          if [ ! -f \"\$input_file\" ]; then
              echo \"Error: Input file \$input_file not found in \$folder_path!\"
              continue
          fi

          # Run nextclade for all sequences from A_HA.txt or B_HA.txt, in order to determine their clade.
          echo \"Running nextclade for \$subtype_folder with file \$input_file...\"
          srun --chdir ${scratch_dir} --output logs/NEXTCLADE_RUN_\${subtype_folder}_%j.log --job-name NEXTCLADE_RUN_\${subtype_folder} --partition short_idx --time 2:00:00 singularity exec -B ${scratch_dir}/../../../ /data/ucct/bi/pipelines/singularity-images/${latest_version_nextclade} nextclade run \"\$input_file\" -d \"\$nextclade_dataset\" -O \"./\$subtype_folder/\" --verbosity info &
      else
          echo \"Warning: Folder \$folder_path does not exist, skipping...\"
      fi
  done < "$AUX_FILE"
" > _01_run_nextclade.sh

# Combine all results into one single file.
echo "
  # Activate the conda environment
  export MAMBA_EXE=\"/data/ucct/bi/pipelines/micromamba/bin/micromamba\"
  export MAMBA_ROOT_PREFIX=\"/data/ucct/bi/pipelines/micromamba\"
  eval \"\$(\$MAMBA_EXE shell hook --shell bash)\"
  micromamba activate biopython_v1.84
  echo -e \"-----Generating nextclade_combined.csv-----\"
  python3 merge_results.py
" > _02_run_merge_results.sh

log_message "Execution completed! Now run the corresponding bash scripts" green