#!/usr/bin/env bash

set -Eeuo pipefail
set -o errtrace
set -o functrace

# Must be executed (not sourced)
if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
	echo "[ERROR] This script must be executed, not sourced: use 'bash $BASH_SOURCE'" >&2
	return 1 2>/dev/null || exit 1
fi

: "${_POLAP_DEBUG:=0}"
export _POLAP_DEBUG
: "${_POLAP_RELEASE:=0}"
export _POLAP_RELEASE

# Resolve repo structure
_polap_script_bin_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" || {
	echo "Couldn't determine the script directory; bailing out." >&2
	exit 2
}
_POLAPLIB_DIR="${_polap_script_bin_dir}/polaplib"

# Optional profiles bootstrap (if present)
# if [[ -r "${_POLAPLIB_DIR}/polap-lib-profiles.sh" ]]; then
# 	# Provides _polap_ensure_profiles_dir (no-op if not used yet)
# 	source "${_POLAPLIB_DIR}/polap-lib-profiles.sh"
# 	_polap_ensure_profiles_dir
# fi

# Core libs: version + arg parsing
source "${_POLAPLIB_DIR}/polap-lib-version.sh"
source "${_POLAPLIB_DIR}/polap-parsing.sh"

# Autoload libraries + traps
# Do not shift "$@" here—just detect the flag.
for __a in "$@"; do
	[[ "$__a" == "--trace-load" ]] && export POLAP_AUTOLOAD_TRACE=1
done
unset __a
source "${_POLAPLIB_DIR}/polap-bash-autoload.sh"
polap_autoload "${_POLAPLIB_DIR}"
polap_enable_failsafe

# polap_trap_enable # installs DEBUG/ERR ring printer

# ───────────────────────────────────────────────────────────────────────────────
# MAIN
# ───────────────────────────────────────────────────────────────────────────────

# Show help if no arguments
if [[ $# -eq 0 ]]; then
	print_help
	touch make-menus
	exit "${EXIT_SUCCESS:-0}"
fi

# Prepare output locations and the log file path
source "${_POLAPLIB_DIR}/polap-variables-main.sh"
_POLAP_COMMAND_LINE="$0 $*"
_polap_timer_reset
_polap_lib_log-init # sets $LOG_FILE and ensures ${_arg_outdir}/{tmp,log} exist
_polap_lib_logfile-clock
_polap_lib_logfile-cmd "${_POLAP_COMMAND_LINE}"
_polap_lib_logfile-args

# ── Dispatch ──────────────────────────────────────────────────────────────────
if declare -f "_run_polap_${_arg_menu[0]}" >/dev/null 2>&1; then
	_polap_log1 "Execute: subcommand ${_arg_menu[0]}"
	"_run_polap_${_arg_menu[0]}"
	_polap_log3 "Menu ${_arg_menu[0]} has been finished."

elif [[ ! -f "${_arg_menu[0]}" ]]; then
	_polap_log0 "-----------------------------------"
	_polap_log0 "Menu: assemble, prepare-polishing, polish"
	_polap_log0 "  assemble1, total-length-long, find-genome-size, reduce-data, flye1, annotate"
	_polap_log0 "  assemble2, select-seeds, map-reads, test-reads, select-reads, flye2"
	_polap_log0 "ERROR: no such menu of $1"

else
	_polap_log1 "Execute: file: ${_arg_menu[0]}"

	_polap_lib_conda-ensure_conda_env polap || exit 1

	# Infer read types from positional args (unchanged logic)
	for _menu_item in "${_arg_menu[@]}"; do
		seqtype=$(_polap_lib_try _polap_lib_fastq-check-type "${_menu_item}" --fallback skip)
		case "$seqtype" in
		illumina)
			_polap_log1 "Detected Illumina short-read: $_menu_item"
			if [[ "${_arg_short_read1_is}" == "on" ]]; then
				_arg_short_read2="${_menu_item}"
				_arg_short_read2_is="on"
				_arg_2_fastq="$_arg_short_read2"
			else
				_arg_short_read1="${_menu_item}"
				_arg_short_read1_is="on"
				_arg_1_fastq="$_arg_short_read1"
			fi
			;;
		pacbio-hifi)
			_polap_log1 "Detected PacBio HiFi read"
			_arg_long_reads="${_menu_item}"
			_arg_long_reads_is="on"
			_arg_long_reads_original="${_arg_long_reads}"
			_arg_l_fastq="${_arg_long_reads}"
			;;
		nano-raw)
			_polap_log1 "Detected Nanopore raw read"
			_arg_long_reads="${_menu_item}"
			_arg_long_reads_is="on"
			_arg_long_reads_original="${_arg_long_reads}"
			_arg_l_fastq="${_arg_long_reads}"
			;;
		unknown)
			_polap_log1 "Could not determine sequencing type ${_menu_item}: pacbio-clr, nano-hq"
			;;
		esac
	done

	_polap_log1 "checking: ${_arg_long_reads}"
	if [[ -s "${_arg_long_reads}" ]]; then
		seqtype=$(_polap_lib_try _polap_lib_fastq-check-type "${_arg_long_reads}" --fallback skip)
		if [[ "$seqtype" == "nano-raw" ]]; then
			_polap_log0 "ONT long-read: ${_arg_long_reads}"
			_arg_data_type="nano-raw"
			_arg_flye_data_type="--nano-raw"
			_arg_minimap2_data_type="map-ont"
		elif [[ "$seqtype" == "pacbio-hifi" ]]; then
			_polap_log0 "PacBio HiFi long-read: ${_arg_long_reads}"
			_arg_data_type="pacbio-hifi"
			_arg_flye_data_type="--pacbio-hifi"
			_arg_minimap2_data_type="map-hifi"
		else
			_polap_log0 "ERROR: no long-read data: ${_arg_long_reads}: ${seqtype}"
		fi
	fi

	if [[ -s "${_arg_short_read1}" ]]; then
		seqtype=$(_polap_lib_fastq-check-type "${_arg_short_read1}")
		if [[ "$seqtype" == "illumina" ]]; then
			_polap_log0 "Short-read 1: ${_arg_short_read1}"
		else
			_polap_log0 "ERROR: no short-read data: ${_arg_short_read1}"
		fi
	else
		_polap_log1 "no short-read data"
	fi

	if [[ -s "${_arg_short_read2}" ]]; then
		seqtype=$(_polap_lib_fastq-check-type "${_arg_short_read2}")
		if [[ "$seqtype" == "illumina" ]]; then
			_polap_log0 "Short-read 2: ${_arg_short_read2}"
		else
			_polap_log0 "ERROR: no short-read data: ${_arg_short_read2}"
		fi
	else
		_polap_log1 "no short-read data"
	fi

	if [[ -s "${_arg_long_reads}" ]]; then
		_polap_log1 "Execute polap assemble"
		_polap_lib_random-init
		_polap_lib_random-get
		_run_polap_assemble
	else
		_polap_log0 "-----------------------------------"
		_polap_log0 "Menu: assemble, prepare-polishing, polish"
		_polap_log0 "  assemble1, total-length-long, find-genome-size, reduce-data, flye1, annotate"
		_polap_log0 "  assemble2, select-seeds, map-reads, test-reads, select-reads, flye2"
		_polap_log0 "ERROR: no such menu of $1"
	fi

	conda deactivate
fi

_polap_lib_logfile-cmd "${_POLAP_COMMAND_LINE}" END
_polap_lib_logfile-elapsed
_polap_lib_logfile-clock
