#!/usr/bin/env bash
# Default: real AQ, automatic data discovery, both stages, one consolidated log.
set -Eeuo pipefail
HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${AQ_ROOT:-/root/disk_3tb/earlywarning/30072026}"
if [[ -n "${AQ_PYTHON:-}" ]]; then PY="$AQ_PYTHON"
elif [[ -n "${PYTHON_BIN:-}" ]]; then PY="$PYTHON_BIN"
elif [[ -x /root/miniconda3/envs/Huy/bin/python3 ]]; then PY=/root/miniconda3/envs/Huy/bin/python3
else PY=python3
fi
cd -- "$HERE"
MODE=aq
STAGE=all
if [[ "${1:-}" == *.json ]]; then
    MODE=config
    CONFIG="$1"; shift
    if [[ "${1:-}" =~ ^(all|development|retrospective)$ ]]; then STAGE="$1"; shift; fi
    LOG_DIR="$("$PY" - "$CONFIG" <<'PYCONFIG'
import json,sys
with open(sys.argv[1]) as f:
    print(json.load(f).get('log_dir','/root/disk_3tb/earlywarning/30072026/log'))
PYCONFIG
)"
    CMD=(-m pace run --config "$CONFIG" --stage "$STAGE" "$@")
else
    if [[ "${1:-}" =~ ^(all|development|retrospective)$ ]]; then STAGE="$1"; shift; fi
    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="$ROOT/log"
    CMD=(-m pace aq-run --root "$ROOT" --stage "$STAGE" "${ARGS[@]}")
fi
MASTER_LOG="${SUITE35_LOG_FILE:-$LOG_DIR/suite35_pace.log}"
mkdir -p -- "$(dirname -- "$MASTER_LOG")"
export PYTHONUNBUFFERED=1
(
    set -Eeuo pipefail
    trap 'status=$?; if (( status == 0 )); then printf "[RUN STATUS] SUCCESS stage=%s exit=%s finished_utc=%s\n" "$STAGE" "$status" "$(date -u +%FT%TZ)"; else printf "[RUN STATUS] FAILURE stage=%s exit=%s finished_utc=%s\n" "$STAGE" "$status" "$(date -u +%FT%TZ)"; fi' EXIT
    printf '\n[START] Suite35 PACE mode=%s stage=%s utc=%s\n' "$MODE" "$STAGE" "$(date -u +%FT%TZ)"
    printf '[CODE] %s\n[ROOT] %s\n[PYTHON] %s\n[LOG] %s\n' "$HERE" "$ROOT" "$PY" "$MASTER_LOG"
    printf '[ARGS]'; printf ' %q' "${CMD[@]}"; printf '\n'
    "$PY" -u "${CMD[@]}"
) 2>&1 | python3 -u "$HERE/pace/stream_log.py" "$MASTER_LOG"
