#!/bin/bash
# Wrapper for claude-usage-fetch.py that alerts on failure
# Used in briefings to ensure we don't go silent on token expiry

SCRIPT_DIR="$(dirname "$0")"
DASHBOARD_URL="http://localhost:9200"

OUTPUT=$("$SCRIPT_DIR/../.venv/bin/python3" "$SCRIPT_DIR/claude-usage-fetch.py" --save 2>&1)
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ] || echo "$OUTPUT" | grep -q "COOKIES_EXPIRED"; then
    echo "⚠️ ALERT: Claude usage fetch FAILED"
    echo "$OUTPUT"
    echo ""
    echo "Cookies need refresh. Get from Chrome:"
    echo "  F12 → Application → Cookies → claude.ai"
    echo "  Copy: sessionKey, cf_clearance"
    echo "  Update: config/claude-cookies.json"
    
    # Update dashboard with error status
    curl -s -X POST "$DASHBOARD_URL/api/status" \
      -H "Content-Type: application/json" \
      -d '{"key": "claude", "value": "⚠️ FETCH FAILED - cookies expired", "type": "error"}' > /dev/null
    
    exit 1
else
    echo "$OUTPUT"
    
    # Get values from saved JSON
    WEEKLY=$(cat /home/johan/clawd/memory/claude-usage.json | jq -r '.weekly_percent // 0')
    REMAINING=$((100 - WEEKLY))
    
    # Determine status type based on usage
    TYPE="info"
    if [ "$WEEKLY" -gt 85 ]; then
        TYPE="error"
    elif [ "$WEEKLY" -gt 70 ]; then
        TYPE="warning"
    fi
    
    # Update dashboard - include check time (no parentheses, dashboard strips those)
    CHECKED=$(date +"%l:%M %p" | xargs)
    curl -s -X POST "$DASHBOARD_URL/api/status" \
      -H "Content-Type: application/json" \
      -d "{\"key\": \"claude\", \"value\": \"${WEEKLY}% used · ${CHECKED}\", \"type\": \"${TYPE}\"}" > /dev/null
    
    echo "📊 Claude: ${WEEKLY}% weekly used (${REMAINING}% left) · checked ${CHECKED}"
fi
