#!/bin/bash
# Gold AutoTrade Watchdog - Health Check Script
# Performs periodic health checks on the gold trading system

# 动态获取当前脚本所在目录
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="$BASE_DIR:$PYTHONPATH"
export LOG_FILE="${BASE_DIR}/logs/.health_check.json"
ERRORS=()

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting health checks..."

# Step 1: Run health check via Python (daemon + EA Bridge 文件状态)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Running health check..."
cd ${BASE_DIR}/bridge && python3 -c '
import sys, os, json, subprocess, datetime, pathlib, time

LOG_FILE = os.environ.get("LOG_FILE")
ERRORS = []

# Check if daemon process is running
result = subprocess.run(["pgrep", "-f", "gold_trader.py"], capture_output=True, text=True)
pids = [p for p in result.stdout.strip().split("\n") if p]
daemon_ok = len(pids) > 0

if not daemon_ok:
    ERRORS.append("gold_trader.py daemon not running")
    print("Daemon: MISSING")
else:
    print(f"Daemon: OK (PIDs: {pids})")

# Check EA Bridge status file (MT5 通信健康度)
mt5_dir = pathlib.Path.home() / "Library" / "Application Support" / "net.metaquotes.wine.metatrader5" / "drive_c" / "users" / "user" / "AppData" / "Roaming" / "MetaQuotes" / "Terminal" / "Common" / "Files"
status_file = mt5_dir / "gold_autotrade" / "bridge" / "terminal_status.json"
bridge_ok = False
if status_file.exists():
    age = time.time() - status_file.stat().st_mtime
    bridge_ok = age < 120
    print(f"Bridge: OK ({age:.0f}s old)" if bridge_ok else f"Bridge: STALE ({age:.0f}s old)")
else:
    print("Bridge: NO_STATUS_FILE")

# Only FAIL on daemon issues (bridge staleness is warned, not failed)
critical_errors = [e for e in ERRORS]
status = "FAIL" if critical_errors else "HEALTHY"
timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+08:00")
health = {
    "timestamp": timestamp,
    "checks": {
        "daemon": "OK" if daemon_ok else "MISSING",
        "bridge": "OK" if bridge_ok else "STALE"
    },
    "status": status,
    "duration_ms": 0,
    "errors": ERRORS
}
with open(LOG_FILE, "w") as f:
    json.dump(health, f, indent=2)
print(f"Health check result: {status}")
' 2>&1

HEALTH_RESULT=$?

# Step 2: Backup daemon liveness check
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Checking for running daemon processes..."
DAEMON_PID=$(pgrep -f "gold_trader.py" 2>/dev/null | /usr/bin/head -1)
if [ -z "$DAEMON_PID" ]; then
    ERRORS+=("Watchdog process not running - need restart")
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Daemon not running, restarting..."
    cd ${BASE_DIR}/bridge && nohup python3 gold_trader.py --daemon > ../logs/daemon.log 2>&1 &
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Daemon restarted"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Daemon is running (PID: $DAEMON_PID)"
fi

# Output summary
if [ ${#ERRORS[@]} -gt 0 ] || [ $HEALTH_RESULT -ne 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] HEALTH CHECK FAILED"
    for err in "${ERRORS[@]}"; do
        echo "  ERROR: ${err}"
    done
    echo ""
    echo "⚠️ 【系统告警】黄金自动交易系统健康检查失败"
    echo "状态：FAIL"
    for err in "${ERRORS[@]}"; do
        echo "异常：${err}"
    done
    exit 1
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Health check completed successfully"
    exit 0
fi
