#!/bin/bash

# Monitor token usage and alert on high consumption
# Can be run as a cron job for proactive monitoring

ALERT_THRESHOLD=${1:-50000}  # Alert at 50k tokens
CRITICAL_THRESHOLD=${2:-100000}  # Critical at 100k tokens

echo "🔍 Token usage monitoring (Alert: ${ALERT_THRESHOLD}, Critical: ${CRITICAL_THRESHOLD})"

# Get current session data
sessions=$(openclaw sessions --json 2>/dev/null)

if [[ $? -ne 0 ]]; then
    echo "❌ Failed to fetch session data"
    exit 1
fi

# Count sessions by threshold
total_sessions=$(echo "$sessions" | jq '.count // 0')
alert_sessions=$(echo "$sessions" | jq --arg threshold "$ALERT_THRESHOLD" '[.sessions[] | select(.totalTokens > ($threshold | tonumber))] | length')
critical_sessions=$(echo "$sessions" | jq --arg threshold "$CRITICAL_THRESHOLD" '[.sessions[] | select(.totalTokens > ($threshold | tonumber))] | length')

# Calculate total token usage
total_tokens=$(echo "$sessions" | jq '[.sessions[] | .totalTokens // 0] | add')

echo "📊 Usage Summary:"
echo "  Total sessions: $total_sessions"
echo "  Alert sessions (>${ALERT_THRESHOLD}): $alert_sessions"
echo "  Critical sessions (>${CRITICAL_THRESHOLD}): $critical_sessions"
echo "  Total tokens: $total_tokens"

# List problematic sessions
if [[ $alert_sessions -gt 0 ]]; then
    echo ""
    echo "⚠️ Sessions requiring attention:"
    echo "$sessions" | jq -r --arg threshold "$ALERT_THRESHOLD" '.sessions[] | select(.totalTokens > ($threshold | tonumber)) | "  \(.key | split(":") | last) - \(.totalTokens) tokens"' | head -10
fi

# Auto-reset critical sessions if requested
if [[ "${AUTO_RESET}" == "true" && $critical_sessions -gt 0 ]]; then
    echo ""
    echo "🔄 Auto-resetting critical sessions..."
    /home/clawd/workspace/scripts/reset-high-token-sessions.sh "$CRITICAL_THRESHOLD" 5
fi

# Exit codes for scripting
if [[ $critical_sessions -gt 0 ]]; then
    exit 2  # Critical level
elif [[ $alert_sessions -gt 0 ]]; then
    exit 1  # Warning level
else
    exit 0  # All good
fi