#!/bin/bash
# Gold Trader wrapper for OpenClaw cron management
# Ensures the gold_trader daemon is running, restarts if dead

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOG="$ROOT/logs/gold_trader.health.log"
PID_FILE="$ROOT/logs/gold_trader.pid"

check_alive() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
            return 0
        fi
    fi
    return 1
}

NOW=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$NOW] Health check" >> "$LOG"

if check_alive; then
    echo "[$NOW] Daemon alive (PID=$(cat $PID_FILE))" >> "$LOG"
else
    echo "[$NOW] Daemon dead, restarting..." >> "$LOG"
    cd "$ROOT"
    nohup python3 bridge/gold_trader.py --daemon --interval 120 >> "$ROOT/logs/gold_trader.daemon.log" 2>&1 &
    echo "[$NOW] Daemon started, PID=$!" >> "$LOG"
fi
