#!/usr/bin/env bash
#
# E8 Markets — drawdown watch.
#
# Polls account limits and alerts when headroom before the daily loss limit
# drops below a threshold. Read-only: it warns, it does not close anything.
#
#   export E8_API_KEY="e8_..."
#   export E8_ACCOUNT_ID="<uuid>"
#   ./e8-risk-watch.sh
#
# Cron (every 15 min, weekday market hours):
#   */15 9-17 * * 1-5  /path/to/e8-risk-watch.sh >> ~/e8/risk.log 2>&1
#
# ~100 calls/day against a 10,000/day budget. Do not tighten the interval
# below 5 minutes — see 04_building_harnesses.md on rate budgeting.

set -euo pipefail

# Alert when fewer than this many PERCENTAGE POINTS of daily drawdown remain.
# e8_account_limits returns room.dailyPct = maxDailyLossPct - used daily drawdown,
# so on a 5% daily limit this starts at 5.0 and falls toward 0. It is NOT a
# percentage of the limit — see 02_tool_reference.md#e8_account_limits.
THRESHOLD="${E8_ROOM_THRESHOLD:-2.0}"
STATE_DIR="${E8_STATE_DIR:-$HOME/e8}"
LAST_ALERT="$STATE_DIR/.last-alert"

: "${E8_API_KEY:?E8_API_KEY is not set}"
: "${E8_ACCOUNT_ID:?E8_ACCOUNT_ID is not set}"

mkdir -p "$STATE_DIR"

notify() {
  local msg="$1"
  echo "[$(date -u +%FT%TZ)] $msg"

  # Wire this to whatever actually reaches you. A log line you never read
  # is not an alert.
  if command -v osascript >/dev/null 2>&1; then
    osascript -e "display notification \"$msg\" with title \"E8 RISK\"" || true
  fi
  # curl -s -X POST "$E8_WEBHOOK_URL" -d "{\"text\":\"$msg\"}" || true
}

RESULT=$(claude -p "Call e8_account_limits for account $E8_ACCOUNT_ID.
Reply with ONLY the raw JSON object the tool returned — no prose, no code
fences, no commentary." 2>/dev/null)

# Strip code fences if the model added them anyway.
RESULT=$(echo "$RESULT" | sed -e 's/^```json//' -e 's/^```//' -e 's/```$//')

if ! echo "$RESULT" | jq -e . >/dev/null 2>&1; then
  # Fail loudly. A silently broken risk watch looks exactly like a calm market.
  notify "risk-watch FAILED to read account limits — check the job"
  exit 1
fi

ROOM=$(echo "$RESULT"     | jq -r '.room.dailyPct // "null"')
EQUITY=$(echo "$RESULT"   | jq -r '.equity')
POSITIONS=$(echo "$RESULT"| jq -r '.positionsCount')
BREACHED=$(echo "$RESULT" | jq -r '.breached.daily or .breached.total or .breached.margin')

echo "[$(date -u +%FT%TZ)] room.dailyPct=${ROOM} equity=${EQUITY} positions=${POSITIONS}"

alert_throttled() {
  # At most one alert an hour, so a bad session doesn't spam you.
  local NOW PREV
  NOW=$(date +%s)
  PREV=$(cat "$LAST_ALERT" 2>/dev/null || echo 0)
  if (( NOW - PREV > 3600 )); then
    notify "$1"
    echo "$NOW" > "$LAST_ALERT"
  fi
}

if [ "$BREACHED" = "true" ]; then
  alert_throttled "LIMIT BREACHED — equity ${EQUITY}, ${POSITIONS} open"
elif [ "$ROOM" = "null" ]; then
  echo "No daily loss limit configured on this account — nothing to watch."
elif (( $(echo "$ROOM < $THRESHOLD" | bc -l) )); then
  alert_throttled "${ROOM} points of daily drawdown left (equity ${EQUITY}, ${POSITIONS} open)"
fi
