#!/bin/bash
# Shared helpers for Ahel automations (M1). Deployed to ~/.ahel/automations/.
AUTO_DIR="$HOME/.ahel/automations"
NTFY="http://127.0.0.1:8099/erebor"
PROM="http://127.0.0.1:9090"
BIFROST="http://127.0.0.1:8081/v1"

# is_disabled <name>  → 0 (true) if a <name>.disabled sentinel exists
is_disabled() { [ -f "$AUTO_DIR/$1.disabled" ]; }

# write_status <name> <title> <schedule> <kind> <ok:0|1> <summary>
write_status() {
  local name="$1" title="$2" sched="$3" kind="$4" ok="$5" summary="$6"
  local enabled=true; is_disabled "$name" && enabled=false
  local okjson=true; [ "$ok" = "1" ] || okjson=false
  python3 - "$name" "$title" "$sched" "$kind" "$okjson" "$enabled" "$summary" >"$AUTO_DIR/$name.status.json" <<'PY'
import json, sys, datetime
n,t,s,k,ok,en,summ = sys.argv[1:8]
print(json.dumps({
  "name": n, "title": t, "schedule": s, "kind": k,
  "last_run": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
  "last_ok": ok == "true", "enabled": en == "true", "summary": summ,
}))
PY
}

# notify <title> <body>
notify() { curl -s -H "Title: $1" -d "$2" "$NTFY" >/dev/null 2>&1; }

# promq <expr> → first value or empty
promq() {
  curl -s "$PROM/api/v1/query" --data-urlencode "query=$1" 2>/dev/null | \
    python3 -c "import json,sys;r=json.load(sys.stdin)['data']['result'];print(r[0]['value'][1] if r else '')" 2>/dev/null
}
