#!/usr/bin/env bash
# scripts/manual/run_client_to_rct_timing_trace_probe.sh
# Manual: client-origin HEVC timing trace layered over the blind RCT probe.
# Not part of CI; requires the live Theia/Tethys lab.

set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
REPO_ROOT="$(cd -- "${SCRIPT_DIR}/../.." >/dev/null 2>&1 && pwd)"
STAMP="$(date +%Y%m%d-%H%M%S)"
LOCAL_OUTPUT_DIR="${LOCAL_OUTPUT_DIR:-/tmp}"
TRACE_DIR="${LOCAL_OUTPUT_DIR%/}/lesavka-client-rct-timing-trace-${STAMP}"
BLIND_DIR="${TRACE_DIR}/blind-probe"
TRACE_JSON="${TRACE_DIR}/client-rct-timing-trace.json"
TRACE_TXT="${TRACE_DIR}/client-rct-timing-trace.txt"
RUN_LOG="${TRACE_DIR}/client-rct-timing-trace-run.log"
mkdir -p "${BLIND_DIR}"
exec > >(tee -a "${RUN_LOG}") 2>&1

echo "==> client-to-RCT T0-T5 timing trace"
echo "   ↪ artifact_dir=${TRACE_DIR}"
echo "   ↪ blind_probe_dir=${BLIND_DIR}"
echo "   ↪ run_log=${RUN_LOG}"
echo "   ↪ this wraps the blind probe and does not reconfigure Theia"

set +e
LOCAL_OUTPUT_DIR="${BLIND_DIR}" "${SCRIPT_DIR}/run_client_to_rct_transport_probe.sh"
blind_status=$?
set -e

probe_dir="$(find "${BLIND_DIR}" -maxdepth 1 -type d -name 'lesavka-client-rct-transport-probe-*' | sort | tail -n 1)"
if [[ -z "${probe_dir}" ]]; then
  echo "no blind probe artifact directory found under ${BLIND_DIR}" >&2
  exit 90
fi

echo "==> building T0-T5 timing trace from ${probe_dir}"
python3 "${SCRIPT_DIR}/client_rct_timing_trace_summary.py" \
  "${probe_dir}" \
  "${TRACE_JSON}" \
  "${TRACE_TXT}"

echo "==> done"
printf '%s\n' \
  "artifact_dir: ${TRACE_DIR}" \
  "blind_probe_artifact_dir: ${probe_dir}" \
  "timing_trace_json: ${TRACE_JSON}" \
  "timing_trace_txt: ${TRACE_TXT}" \
  "run_log: ${RUN_LOG}" \
  "blind_probe_exit_status: ${blind_status}"

exit "${blind_status}"
