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

RUNNER="/home/agent/.local/state/CryptoTradingBot/run_focused_paper_fleet.sh"
PROJECT="/home/agent/projects/CryptoTradingBot/Crypto_Agent"
RUNTIME="/home/agent/.local/state/CryptoTradingBot"
EXPECTED=(
  "candidate_v66_squeeze_breakout_sampler"
  "candidate_v69_squeeze_breakout_confirmed"
  "candidate_v74_relative_strength_breadth_guard"
  "candidate_v75_hybrid_survival_squeeze"
)

read_env_value() {
  local pid="$1" key="$2"
  tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null | awk -F= -v k="$key" '$1==k {print substr($0, length(k)+2); exit}'
}

is_expected() {
  local sid="$1"
  for expected in "${EXPECTED[@]}"; do
    [[ "$sid" == "$expected" ]] && return 0
  done
  return 1
}

# Avoid restart thrash during DNS/API incidents.
if ! curl -fsS --max-time 8 -H 'Content-Type: application/json' -d '{"type":"meta"}' https://api.hyperliquid.xyz/info >/dev/null 2>&1; then
  echo "Crypto paper watchdog: Hyperliquid API/DNS not reachable; no restart attempted."
  exit 0
fi

need_restart=0
reason=()

for sid in "${EXPECTED[@]}"; do
  count=0
  while read -r pid; do
    [[ -z "$pid" ]] && continue
    psid="$(read_env_value "$pid" CTB_STRATEGY_ID || true)"
    paper="$(read_env_value "$pid" CTB_PAPER_TRADING || true)"
    dry="$(read_env_value "$pid" CTB_DRY_RUN || true)"
    if [[ "$psid" == "$sid" && "$paper" == "true" && "$dry" == "false" ]]; then
      ((count+=1))
    fi
  done < <(pgrep -f '^/home/agent/projects/CryptoTradingBot/Crypto_Agent/.venv/bin/python AutoTrader.py$' || true)
  if [[ "$count" -ne 1 ]]; then
    need_restart=1
    reason+=("$sid count=$count")
  fi
done

while read -r pid; do
  [[ -z "$pid" ]] && continue
  sid="$(read_env_value "$pid" CTB_STRATEGY_ID || true)"
  paper="$(read_env_value "$pid" CTB_PAPER_TRADING || true)"
  dry="$(read_env_value "$pid" CTB_DRY_RUN || true)"
  rdir="$(read_env_value "$pid" CTB_RUNTIME_DIR || true)"
  if [[ "$rdir" == "$RUNTIME"/experiments/* ]]; then
    if ! is_expected "$sid" || [[ "$paper" != "true" || "$dry" != "false" ]]; then
      need_restart=1
      reason+=("unexpected/unsafe pid=$pid strategy=$sid paper=$paper dry=$dry")
    fi
  fi
done < <(pgrep -f '^/home/agent/projects/CryptoTradingBot/Crypto_Agent/.venv/bin/python AutoTrader.py$' || true)

if [[ "$need_restart" == 0 ]]; then
  exit 0
fi

out="$($RUNNER 2>&1)"
status=$?
if [[ "$status" -eq 0 ]]; then
  echo "Crypto paper watchdog: focused fleet repaired. Reason: ${reason[*]}. ${out}" | tr '\n' ' '
else
  echo "Crypto paper watchdog ERROR: repair failed status=$status. Reason: ${reason[*]}. ${out}" | tr '\n' ' '
fi
exit "$status"
