#!/bin/bash
# Gold Trader 健康检查脚本（OpenClaw cron 兜底版本）
# 调用 watchdog.sh 执行实际检查，自己只写 JSON 报告文件
# watchdog.sh 已包含全部检查逻辑

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_DIR="$ROOT_DIR/logs"
HEALTH_FILE="$LOG_DIR/.health_check.json"

NOW=$(date '+%Y-%m-%dT%H:%M:%S+08:00')

# 执行 watchdog.sh 获取结果
RESULT=$(bash "$ROOT_DIR/watchdog.sh" 2>&1)
EXIT_CODE=$?

# 解析 watchdog 输出
if [ $EXIT_CODE -eq 0 ]; then
    STATUS="OK"
    ERRORS="[]"
    WARNINGS="[]"
else
    STATUS="FAIL"
    # 提取异常项
    ISSUES=$(echo "$RESULT" | grep "^  -" | sed 's/  - //' | python3 -c 'import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))' 2>/dev/null)
    ERRORS="${ISSUES:-[]}"
    WARNINGS="[]"
fi

# 写入 JSON 报告
python3 - "$NOW" "$STATUS" "$ERRORS" "$WARNINGS" "$HEALTH_FILE" << 'PYEOF'
import json, sys
now, status, errors, warnings, health_file = sys.argv[1:]
try:
    errors = json.loads(errors)
except:
    errors = []
try:
    warnings = json.loads(warnings)
except:
    warnings = []
report = {
    "timestamp": now,
    "status": status,
    "errors": errors,
    "warnings": warnings,
    "raw_output": sys.stdin.read() if False else ""
}
with open(health_file, "w") as f:
    json.dump(report, f, ensure_ascii=False, indent=2)
PYEOF

# 输出人类可读结果
echo "$RESULT"
exit $EXIT_CODE
