#!/usr/bin/env bash
# Suite32 canonical runner. Captures stdout AND stderr to the project's log folder.
set -Eeuo pipefail
HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${AQ_ROOT:-/root/disk_3tb/earlywarning/30072026}"
PY="${AQ_PYTHON:-/root/miniconda3/envs/Huy/bin/python3}"
STAGE="${1:-preflight}"
if (( $# > 0 )); then shift; fi

# The Python entry point permits --root to override AQ_ROOT. Keep logs under
# the effective root, including when users supply --root after the stage.
ARGS=("$@")
for (( i=0; i<${#ARGS[@]}; i++ )); do
    case "${ARGS[i]}" in
        --root)
            if (( i+1 < ${#ARGS[@]} )); then ROOT="${ARGS[i+1]}"; fi
            ;;
        --root=*) ROOT="${ARGS[i]#--root=}" ;;
    esac
done

LOG_DIR="${SUITE32_LOG_DIR:-$ROOT/log}"
MASTER_LOG="${SUITE32_LOG_FILE:-$LOG_DIR/suite32_selective_borrowing.log}"
STAGE_LOG="$LOG_DIR/suite32_selective_borrowing_${STAGE}.log"
RUN_ID="$(date +%Y%m%dT%H%M%S)_$$"
RUN_LOG="$LOG_DIR/suite32_selective_borrowing_runs/${STAGE}_${RUN_ID}.log"
RESULTS="$ROOT/results/suite32_selective_borrowing"
for (( i=0; i<${#ARGS[@]}; i++ )); do
    case "${ARGS[i]}" in
        --output-dir)
            if (( i+1 < ${#ARGS[@]} )); then RESULTS="${ARGS[i+1]}"; fi
            ;;
        --output-dir=*) RESULTS="${ARGS[i]#--output-dir=}" ;;
    esac
done
mkdir -p -- "$(dirname -- "$MASTER_LOG")" "$(dirname -- "$STAGE_LOG")" "$(dirname -- "$RUN_LOG")"

# No silent pipe failures: pipefail preserves the Python exit status even though
# tee prints the output to both terminal and files. Keep one canonical append-
# only log across stages, a stage-latest log, and an immutable per-invocation log.
(
    set -Eeuo pipefail
    trap 'status=$?; if (( status == 0 )); then printf "[RUN STATUS] SUCCESS stage=%s exit=%s finished=%s\n" "$STAGE" "$status" "$(date -Is)"; else printf "[RUN STATUS] FAILURE stage=%s exit=%s finished=%s\n" "$STAGE" "$status" "$(date -Is)"; fi' EXIT
    echo '========================================================================================================================'
    printf '[START] %s Suite32 selective borrowing stage=%s run=%s\n' "$(date -Is)" "$STAGE" "$RUN_ID"
    printf '[CODE] %s\n[ROOT] %s\n[PYTHON] %s\n' "$HERE" "$ROOT" "$PY"
    printf '[LOG] %s\n[STAGE LOG] %s\n[RUN LOG] %s\n[RESULTS] %s\n' "$MASTER_LOG" "$STAGE_LOG" "$RUN_LOG" "$RESULTS"
    printf '[ARGS]'; printf ' %q' "--stage" "$STAGE" "--root" "$ROOT" "${ARGS[@]}"; printf '\n'
    cd -- "$HERE"
    "$PY" -u train_suite32.py --stage "$STAGE" --root "$ROOT" "${ARGS[@]}"
) 2>&1 | tee -a -- "$MASTER_LOG" "$RUN_LOG" | tee -- "$STAGE_LOG"
