#!/usr/bin/env bash
# ── Timmy Loop Watchdog ────────────────────────────────────────────────
# Checks if the timmy-loop tmux session is alive. Restarts if dead.
# Designed to run via cron every 5 minutes.
# ───────────────────────────────────────────────────────────────────────

SESSION="timmy-loop"
LAUNCHER="$HOME/.hermes/bin/timmy-tmux.sh"
WATCHDOG_LOG="$HOME/Timmy-Time-dashboard/.loop/watchdog.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$WATCHDOG_LOG"
}

# Check if tmux session exists
if tmux has-session -t "$SESSION" 2>/dev/null; then
    # Session exists. Check if the loop pane (pane 0) is still running.
    PANE0_PID=$(tmux list-panes -t "$SESSION:.0" -F '#{pane_pid}' 2>/dev/null)
    if [ -n "$PANE0_PID" ] && kill -0 "$PANE0_PID" 2>/dev/null; then
        # All good, loop is alive
        exit 0
    else
        log "WARN: Session exists but loop pane is dead. Restarting..."
        tmux kill-session -t "$SESSION" 2>/dev/null
    fi
else
    log "WARN: Session '$SESSION' not found."
fi

# Check for a stop file — lets Alexander or an agent halt the loop
if [ -f "$HOME/Timmy-Time-dashboard/.loop/STOP" ]; then
    log "STOP file found. Not restarting. Remove .loop/STOP to resume."
    exit 0
fi

log "Restarting timmy-loop session..."
export PATH="$HOME/.local/bin:$HOME/.hermes/bin:$PATH"
"$LAUNCHER"
log "Session restarted."
