#!/bin/bash

# Reset sessions with token usage above specified threshold
# Usage: ./reset-high-token-sessions.sh [threshold] [max_resets]

THRESHOLD=${1:-50000}  # Default 50k tokens
MAX_RESETS=${2:-10}    # Default max 10 resets per run

echo "🔧 Resetting sessions with >${THRESHOLD} tokens (max ${MAX_RESETS} resets)"

# Get sessions list using gateway call
SESSIONS=$(openclaw gateway call sessions.list --params '{"limit": 50}' 2>/dev/null)

if [ -z "$SESSIONS" ]; then
  echo "❌ Failed to get sessions list"
  exit 1
fi

# Process sessions using Python (no jq dependency)
python3 -c "
import json
import subprocess
import sys
import time

# Parse the sessions data
data = json.loads('''$SESSIONS''')
sessions = data.get('sessions', [])

# Find high-token sessions
high_token_sessions = [(s['key'], s.get('totalTokens', 0)) for s in sessions if s.get('totalTokens', 0) > $THRESHOLD]
high_token_sessions = high_token_sessions[:$MAX_RESETS]  # Limit resets

if not high_token_sessions:
    print('✅ No sessions over ${THRESHOLD} tokens found')
    sys.exit(0)

print(f'Found {len(high_token_sessions)} sessions to reset:')

# Reset each session
for session_key, token_count in high_token_sessions:
    print(f'🔄 Resetting: {session_key} ({token_count} tokens)')
    
    # Call reset via subprocess
    cmd = ['openclaw', 'gateway', 'call', 'sessions.reset', '--params', f'{{\"key\": \"{session_key}\"}}']
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        try:
            reset_data = json.loads(result.stdout)
            if reset_data.get('ok'):
                print('✅ Reset successful')
            else:
                print('❌ Reset failed (not ok)')
        except:
            print('❌ Reset failed (parse error)')
    else:
        print('❌ Reset failed (command error)')
    
    # Small delay to avoid rate limiting
    time.sleep(0.5)
"

echo "🏁 Session reset complete"