#!/usr/bin/env bash
#
# E8 Markets — morning brief.
#
# Writes a dated pre-session summary: account standing, open positions,
# overnight ranges, recent news. Read-only; places no orders.
#
#   export E8_API_KEY="e8_..."
#   export E8_ACCOUNT_ID="<uuid from e8_accounts_list>"
#   ./e8-morning-brief.sh
#
# Cron (weekdays, 07:00):
#   0 7 * * 1-5  /path/to/e8-morning-brief.sh >> ~/e8/brief.log 2>&1

set -euo pipefail

OUT_DIR="${E8_BRIEF_DIR:-$HOME/e8}"
OUT_FILE="$OUT_DIR/brief-$(date +%Y-%m-%d).md"

: "${E8_API_KEY:?E8_API_KEY is not set}"
: "${E8_ACCOUNT_ID:?E8_ACCOUNT_ID is not set — run e8_accounts_list to find it}"

mkdir -p "$OUT_DIR"

claude -p "Using the e8-terminal MCP tools, write my pre-session brief.

Account: $E8_ACCOUNT_ID

1. e8_account_limits — equity, and room remaining before the daily and total
   loss limits.
2. e8_positions_list — every open position with unrealized P&L.
3. For each symbol I hold, e8_trade_history with resolution '60' and
   countBack 24 — note the overnight high, low, and where price sits in that
   range now.
4. e8_news with timeWindow '24H', limit 10.

Write ONE paragraph covering: where the account stands, what my open risk
looks like, what moved overnight, and anything in the news touching symbols
I hold. Then a short bullet list of any position within 20% of its stop.

Report facts only. Do not suggest trades, entries, exits, or direction." \
  > "$OUT_FILE"

echo "Brief written to $OUT_FILE"

# Optional: surface it immediately on macOS.
if command -v osascript >/dev/null 2>&1; then
  osascript -e 'display notification "Morning brief ready" with title "E8 Markets"' || true
fi
