#!/bin/bash
# Log Claude usage to SQLite and alert on rapid consumption
# Alerts if weekly_percent increases by 4+ points in any 2-hour window

set -euo pipefail

SCRIPT_DIR="$(dirname "$0")"
DB="$SCRIPT_DIR/../memory/claude-usage.db"
USAGE_JSON="$SCRIPT_DIR/../memory/claude-usage.json"
SIGNAL_SKILL="$SCRIPT_DIR/../skills/signal-notify"

# Run the fetch first
"$SCRIPT_DIR/claude-usage-check.sh" || true

# Read current values
WEEKLY=$(jq -r '.weekly_percent // 0' "$USAGE_JSON")
SESSION=$(jq -r '.session_percent // 0' "$USAGE_JSON")
SONNET=$(jq -r '.sonnet_percent // 0' "$USAGE_JSON")

# Create DB and table if needed
sqlite3 "$DB" <<'SQL'
CREATE TABLE IF NOT EXISTS usage_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    ts TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
    weekly_percent INTEGER NOT NULL,
    session_percent INTEGER NOT NULL,
    sonnet_percent INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage_log(ts);
SQL

# Insert current reading
sqlite3 "$DB" "INSERT INTO usage_log (weekly_percent, session_percent, sonnet_percent) VALUES ($WEEKLY, $SESSION, $SONNET);"

# Check 2-hour delta: get the reading from ~2 hours ago
TWO_HR_AGO=$(sqlite3 "$DB" "SELECT weekly_percent FROM usage_log WHERE ts <= strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-2 hours') ORDER BY ts DESC LIMIT 1;")

if [ -n "$TWO_HR_AGO" ]; then
    DELTA=$((WEEKLY - TWO_HR_AGO))
    if [ "$DELTA" -ge 4 ]; then
        echo "🚨 ALERT: Claude usage jumped ${DELTA}% in 2 hours (${TWO_HR_AGO}% → ${WEEKLY}%)"
        # Exit 2 signals the cron agent to alert Johan
        exit 2
    fi
fi

echo "Logged: ${WEEKLY}% weekly (delta from 2h ago: ${DELTA:-n/a}%)"
exit 0
