#!/usr/bin/env bash
# Live state of the repricer merge/sync in the terminal. Exit: Ctrl-C (does not affect the merge/sync itself).
#   ./watch.sh           merge, refresh every 15 s
#   ./watch.sh 5         every 5 s
#   ./watch.sh 15 sync   prod sync (sync.py)
D="$(cd "$(dirname "$0")" && pwd)"
INT="${1:-15}"
MODE="${2:-merge}"
if [ "$MODE" = sync ]; then PY=sync.py; LOGPAT='bg-sync*'; else PY=merge.py; LOGPAT='bg-merge*'; fi
trap 'tput cnorm 2>/dev/null; echo; exit 0' INT TERM
tput civis 2>/dev/null

while true; do
  out="$(
    # 1) the process
    s=$(bgls 2>/dev/null | grep -E "${LOGPAT%\*}" | head -1)
    run=$(pgrep -u "$USER" -f "^python3 $PY" | grep -v $$ | head -1)
    if [ -n "$run" ]; then echo "Process $PY: RUNNING (pid $run)"; else echo "Process $PY: not running"; fi
    [ -n "$s" ] && echo "Latest bg session: $s"
    echo

    # 2) metrics (live, from the state file)
    python3 "$D/$PY" --status 2>&1
    echo

    # 3) local MySQL
    if docker ps --format '{{.Names}}' | grep -qx repricer-db; then
      q=$(docker exec repricer-db mysql --defaults-extra-file=/secrets/local.cnf -N -e \
        "select count(*) from information_schema.processlist where command='Query' and info not like '%processlist%'" 2>/dev/null)
      echo "Local MySQL: up, active queries: ${q:-?}"
    else
      echo "Local MySQL: CONTAINER NOT RUNNING"
    fi
    echo "Disk: $(df -h --output=avail "${REPRICER_DB_DIR:-$HOME/projects/new-repricer-db}" | tail -1 | tr -d " ") free"
    r0=$(cat /sys/class/net/enp118s0/statistics/rx_bytes); sleep 2; r1=$(cat /sys/class/net/enp118s0/statistics/rx_bytes)
    mb=$(( (r1 - r0) * 8 / 2 / 1000000 ))
    echo "Link now (all inbound on enp118s0): ${mb} Mbit/s of ~300, $(( mb * 100 / 300 ))%; cap 150 Mbit/s (50%)"
    echo

    # 4) latest log events
    log=$(ls -t ~/logs/$LOGPAT.log 2>/dev/null | head -1)
    if [ -n "$log" ]; then
      echo "Log $log (latest errors/events):"
      grep -E 'ERROR|STOP|DONE|TEST|fresh:|schema:|schema_check:|plan:|load:|bbph_gap:|indexes:|verify:|preflight:|redo-gap' "$log" | tail -6 | cut -c1-200
    fi
  )"
  clear
  echo "$out"
  echo
  echo "refresh every ${INT}s, $(date '+%H:%M:%S'), Ctrl-C to exit"
  sleep "$INT"
done
