#!/usr/bin/env bash
# scripts/manual/client_rct_uvc_frame_meta_fetch.sh
# Manual: optional UVC spool metadata fetch for client-to-RCT lab probes.
# Not part of CI; requires SSH access to a live server artifact.
# Fetches optional server-side UVC spool timing for client-to-RCT probes.

set -euo pipefail

if [[ "$#" -ne 9 ]]; then
  echo "usage: $0 SERVER_HOST REMOTE_LOG REQUIRED LOCAL_JSONL SUMMARY_JSON SUMMARY_TXT TIMELINE_JSON MODE_FPS REPO_ROOT" >&2
  exit 2
fi

server_host=$1
remote_log=$2
required=$3
local_jsonl=$4
summary_json=$5
summary_txt=$6
timeline_json=$7
mode_fps=$8
repo_root=$9
ssh_opts=${SSH_OPTS:-"-o BatchMode=yes -o ConnectTimeout=5"}

if [[ -z "${remote_log}" ]]; then
  echo "==> UVC frame metadata log fetch disabled"
  echo "   ↪ set LESAVKA_CLIENT_RCT_UVC_FRAME_META_LOG_REMOTE to fetch and summarize server-side spool timing"
  exit 0
fi

echo "==> fetching optional UVC frame metadata log from ${server_host}:${remote_log}"
if ! scp ${ssh_opts} "${server_host}:${remote_log}" "${local_jsonl}"; then
  if [[ "${required}" == "1" ]]; then
    echo "required UVC frame metadata log was unavailable" >&2
    exit 91
  fi
  echo "   ↪ optional UVC frame metadata log unavailable; continuing without spool-boundary summary"
  exit 0
fi

summarize_args=(
  "${local_jsonl}"
  "${summary_json}"
  "${summary_txt}"
  --timeline "${timeline_json}"
)
if [[ "${mode_fps}" != "0" ]]; then
  summarize_args+=(--fps "${mode_fps}")
fi
if ! python3 "${repo_root}/scripts/manual/summarize_uvc_frame_meta_log.py" "${summarize_args[@]}"; then
  if [[ "${required}" == "1" ]]; then
    echo "required UVC frame metadata log could not be summarized" >&2
    exit 92
  fi
  echo "   ↪ optional UVC frame metadata log could not be summarized; continuing without spool-boundary summary"
fi
