#!/usr/bin/env bash
# ── Hermes System Watchdog ─────────────────────────────────────────────
# Monitors all critical services. Restarts anything that's dead.
# Runs via hermes cron every 8 minutes.
#
# Watches:
#   1. timmy-loop tmux session (4-pane dev dashboard)
#   2. Webhook listener on port 7777 (Gitea comment watcher)
#   3. Gitea on port 3000 (just reports, can't restart homebrew services)
#   4. Ollama on port 11434 (just reports)
# ───────────────────────────────────────────────────────────────────────

export PATH="/opt/homebrew/bin:$HOME/.local/bin:$HOME/.hermes/bin:/usr/local/bin:$PATH"

WATCHDOG_LOG="$HOME/Timmy-Time-dashboard/.loop/watchdog.log"
mkdir -p "$(dirname "$WATCHDOG_LOG")"

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

STATUS="ok"

# ── 1. Timmy Loop ──────────────────────────────────────────────────────

SESSION="timmy-loop"
LAUNCHER="$HOME/.hermes/bin/timmy-tmux.sh"
STOP_FILE="$HOME/Timmy-Time-dashboard/.loop/STOP"

if [ -f "$STOP_FILE" ]; then
    log "timmy-loop: STOPPED (STOP file present)"
elif tmux has-session -t "$SESSION" 2>/dev/null; then
    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
        : # alive, say nothing
    else
        log "timmy-loop: pane dead, restarting..."
        tmux kill-session -t "$SESSION" 2>/dev/null
        "$LAUNCHER"
        log "timmy-loop: restarted"
        STATUS="repaired"
    fi
else
    log "timmy-loop: session missing, starting..."
    "$LAUNCHER"
    log "timmy-loop: started"
    STATUS="repaired"
fi

# ── 2. Webhook Listener (port 7777) ────────────────────────────────────

if lsof -ti:7777 >/dev/null 2>&1; then
    : # alive
else
    log "webhook: dead, restarting..."
    tmux has-session -t webhook 2>/dev/null && tmux kill-session -t webhook
    tmux new-session -d -s webhook "python3 $HOME/.hermes/bin/gitea-webhook-listener.py"
    sleep 2
    if lsof -ti:7777 >/dev/null 2>&1; then
        log "webhook: restarted on port 7777"
        STATUS="repaired"
    else
        log "webhook: FAILED to restart"
        STATUS="degraded"
    fi
fi

# ── 3. Gitea (port 3000) — report only ─────────────────────────────────

if ! lsof -ti:3000 >/dev/null 2>&1; then
    log "gitea: NOT RUNNING on port 3000 — try: brew services start gitea"
    STATUS="degraded"
fi

# ── 4. Ollama (port 11434) — report only ───────────────────────────────

if ! lsof -ti:11434 >/dev/null 2>&1; then
    log "ollama: NOT RUNNING on port 11434 — open Ollama.app"
    STATUS="degraded"
fi

# Only log if something needed fixing
if [ "$STATUS" != "ok" ]; then
    log "watchdog: status=$STATUS"
fi
