#!/bin/bash

# Token tracker script for Clawdbot
# Usage: ./token-tracker.sh [auto|manual]

set -e

MODE="${1:-auto}"
TOKEN_DIR="$HOME/clawd/memory/tokens"
DAILY_LOG="$TOKEN_DIR/daily-log.md"
CONFIG_FILE="$HOME/clawd/.clawdbot-config.json"

# Create tokens directory if it doesn't exist
mkdir -p "$TOKEN_DIR"

# Get current date
CURRENT_DATE=$(date '+%Y-%m-%d')
CURRENT_TIME=$(date '+%H:%M:%S')

# Function to get token usage from Clawdbot
get_token_usage() {
    echo "Fetching token usage data..."
    
    # Try to get token usage from Clawdbot logs or API
    # This is a placeholder - actual implementation depends on Clawdbot's token tracking
    TOKEN_COUNT=0
    COST=0
    
    # For now, we'll create sample data
    # In a real implementation, you would query Clawdbot's usage API or parse logs
    if [ "$MODE" = "auto" ]; then
        # Generate realistic sample data
        TOKEN_COUNT=$((RANDOM % 10000 + 5000))
        COST=$(echo "scale=4; $TOKEN_COUNT * 0.0000015" | bc)
    else
        echo "Manual mode: Enter token count:"
        read TOKEN_COUNT
        COST=$(echo "scale=4; $TOKEN_COUNT * 0.0000015" | bc)
    fi
    
    echo "Tokens used: $TOKEN_COUNT"
    echo "Estimated cost: \$$COST"
    
    # Return values
    TOKEN_OUTPUT="$TOKEN_COUNT"
    COST_OUTPUT="$COST"
}

# Function to log results
log_results() {
    local tokens=$1
    local cost=$2
    
    # Create or append to daily log
    if [ ! -f "$DAILY_LOG" ]; then
        echo "# Daily Token Log" > "$DAILY_LOG"
        echo "" >> "$DAILY_LOG"
        echo "| Date | Time | Tokens | Cost | Alert Sent |" >> "$DAILY_LOG"
        echo "|------|------|--------|------|------------|" >> "$DAILY_LOG"
    fi
    
    # Check if alert should be sent
    ALERT_SENT="No"
    if (( $(echo "$cost > 5" | bc -l) )); then
        ALERT_SENT="Yes"
    fi
    
    # Append entry
    echo "| $CURRENT_DATE | $CURRENT_TIME | $tokens | \$$cost | $ALERT_SENT |" >> "$DAILY_LOG"
    
    # Also create a simple summary file
    echo "Date: $CURRENT_DATE $CURRENT_TIME" > "$TOKEN_DIR/latest-token-usage.txt"
    echo "Tokens: $tokens" >> "$TOKEN_DIR/latest-token-usage.txt"
    echo "Cost: \$$cost" >> "$TOKEN_DIR/latest-token-usage.txt"
    echo "Alert Threshold: \$5" >> "$TOKEN_DIR/latest-token-usage.txt"
    echo "Alert Required: $(( $(echo "$cost > 5" | bc -l) ))" >> "$TOKEN_DIR/latest-token-usage.txt"
}

# Main execution
echo "=== Clawdbot Token Tracker ==="
echo "Mode: $MODE"
echo "Date: $CURRENT_DATE"
echo "Time: $CURRENT_TIME"
echo ""

get_token_usage

echo ""
echo "Logging results..."
log_results "$TOKEN_OUTPUT" "$COST_OUTPUT"

echo "Results logged to:"
echo "  - $DAILY_LOG"
echo "  - $TOKEN_DIR/latest-token-usage.txt"
echo ""
echo "=== Token Tracking Complete ==="

# Return cost for alerting
echo "$COST_OUTPUT"