#!/bin/bash

# Default parameters
FASTA_FILE=""
TARGET=""
OUTPUT_DIR=""
PAF_FILE=""
CHUNK_SIZE=100000
TEMP_DIR=$(mktemp -d)

# Help message
show_help() {
cat << EOF
Usage: ${0##*/} [-h] -f FASTA_FILE -t TARGET -o OUTPUT_DIR -p PAF_FILE

Automates the process of visualizing pangenome graphs in JBrowse from the pggb output.

    -h          display this help and exit
    -f FILE     specify the fasta file containing sequences used in pggb graph building
    -t TARGET   specify the reference assembly name
    -o DIR      specify the output directory for visualization files
    -p FILE     specify the PAF file generated by pggb

EOF
}

# Parse command-line options
while getopts "hf:t:o:p:" opt; do
    case "${opt}" in
        h)
            show_help
            exit 0
            ;;
        f)  FASTA_FILE=${OPTARG}
            ;;
        t)  TARGET=${OPTARG}
            ;;
        o)  OUTPUT_DIR=${OPTARG}
            ;;
        p)  PAF_FILE=${OPTARG}
            ;;
        '?')
            show_help >&2
            exit 1
            ;;
    esac
done

# Verify required parameters
if [ -z "${FASTA_FILE}" ] || [ -z "${TARGET}" ] || [ -z "${OUTPUT_DIR}" ] || [ -z "${PAF_FILE}" ]; then
    echo "Missing required parameters." >&2
    show_help >&2
    exit 1
fi

# Verify that temporary directory was successfully created
if [ ! -d "${TEMP_DIR}" ]; then
    echo "Failed to create a temporary directory." >&2
    exit 1
fi

# Step 2: Convert PAF to MAF
OUTPUT_MAF="${TEMP_DIR}/${TARGET}.maf"
echo "wgatools pafpseudo -f ${FASTA_FILE} -g ${TARGET} -o ${OUTPUT_MAF} ${PAF_FILE}"
wgatools pafpseudo -f "${FASTA_FILE}" -g "${TARGET}" -o "${OUTPUT_MAF}" "${PAF_FILE}"

# Step 3: Chunk the MAF file
CHUNKED_MAF="${TEMP_DIR}/chunked_${TARGET}.maf"
mafchunk "${OUTPUT_MAF}" "${CHUNK_SIZE}" > "${CHUNKED_MAF}"

# Step 4: Create pseudo-BED for mafviewer
PSEUDO_BED="${OUTPUT_DIR}/out.bed.gz"
cat "${CHUNKED_MAF}" | maf2bed "${TARGET}" | bgzip > "${PSEUDO_BED}"

# Step 5: Index the pseudo-BED
tabix -p bed "${PSEUDO_BED}"

echo "Visualization files prepared. Please proceed with JBrowse setup and visualization steps."
echo "Temporary files are located in: ${TEMP_DIR}"

# Clean up if necessary
# rm -r "${TEMP_DIR}"
