#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
logs_dir="$repo_root/outputs/logs"
model_dir="$repo_root/outputs/model_outputs/latest"

latest_log="$(ls "$logs_dir"/full_run_*.log 2>/dev/null | sort | tail -n 1 || true)"
latest_run="$(ls -d "$model_dir"/run_* 2>/dev/null | sort | tail -n 1 || true)"

echo "party2d full-run progress"
echo "repo: $repo_root"
echo

if [[ -n "$latest_log" ]]; then
  echo "Latest durable log: $latest_log"
  echo "--- last 40 log lines ---"
  tail -n 40 "$latest_log"
else
  echo "No durable full_run_*.log found under $logs_dir"
fi

echo
if [[ -n "$latest_run" ]]; then
  echo "Latest model run: $latest_run"
  metrics="$latest_run/diagnostics/run_metrics.json"
  if [[ -f "$metrics" ]]; then
    echo "Metrics: $metrics"
    echo "--- key metrics ---"
    py="$(command -v python3 || command -v python || true)"
    if [[ -z "$py" && -x /run/current-system/sw/bin/python3 ]]; then
      py=/run/current-system/sw/bin/python3
    fi
    if [[ -z "$py" ]]; then
      echo "No Python interpreter found for JSON summary; metrics file is available at: $metrics"
      exit 0
    fi
    "$py" - "$metrics" <<'PY'
import json, sys
path = sys.argv[1]
with open(path) as f:
    m = json.load(f)
print("status:", m.get("status"))
cfg = m.get("config", {})
print("chains:", cfg.get("num_chains"), "warmup:", cfg.get("num_warmup"), "samples:", cfg.get("num_samples"), "max_depth:", cfg.get("max_depth"), "refresh:", cfg.get("refresh"))
timing = m.get("timing", {})
if timing:
    print("walltime_minutes:", timing.get("walltime_minutes"))
    print("reported_warmup_seconds:", timing.get("reported_warmup_seconds"))
    print("reported_sampling_seconds:", timing.get("reported_sampling_seconds"))
agg = m.get("aggregate", {})
if agg:
    print("divergences:", agg.get("divergences"), "treedepth_hits:", agg.get("treedepth_hits"), "mean_leapfrog:", agg.get("mean_leapfrog"))
print("cmdstan_config_verified:", m.get("cmdstan_config_verified"))
PY
  else
    echo "No archived metrics yet. If the run is still sampling, watch the durable log with:"
    if [[ -n "$latest_log" ]]; then
      echo "  tail -f \"$latest_log\""
    else
      echo "  tail -f outputs/logs/full_run_<timestamp>.log"
    fi
  fi
else
  echo "No completed model run found under $model_dir"
fi

echo
echo "To follow a running job live:"
if [[ -n "$latest_log" ]]; then
  echo "  tail -f \"$latest_log\""
else
  echo "  tail -f outputs/logs/full_run_<timestamp>.log"
fi
