#!/usr/bin/env bash
set -euo pipefail

ROOT="/opt/microdao-daarion"
STATUS_DIR="$ROOT/ops/status"
STATUS_JSON="$STATUS_DIR/canary_all.latest.json"
STATUS_LOG="$STATUS_DIR/canary_all.latest.log"
TS_START="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

mkdir -p "$STATUS_DIR"

set +e
out="$(cd "$ROOT" && bash ./ops/canary_all.sh 2>&1)"
rc=$?
set -e

printf '%s\n' "$out" > "$STATUS_LOG"
TS_END="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

status="ok"
if [[ $rc -ne 0 ]]; then
  status="fail"
fi

python3 - <<PY
import json
from pathlib import Path
payload = {
  "status": "$status",
  "exit_code": $rc,
  "started_at": "$TS_START",
  "ended_at": "$TS_END",
  "log_path": "$STATUS_LOG"
}
Path("$STATUS_JSON").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(payload, ensure_ascii=False))
PY

# Optional notify to SOFIIA (non-fatal for canary status)
set +e
notify_out="$(bash "$ROOT/ops/monitor_notify_sofiia.sh" "$STATUS_JSON" 2>&1)"
notify_rc=$?
set -e
printf '%s\n' "$notify_out" >> "$STATUS_LOG"
if [[ $notify_rc -ne 0 ]]; then
  echo "[WARN] sofiia notify failed (rc=$notify_rc)"
fi

exit $rc
