#!/usr/bin/env zsh

# RT Cache Manager - Intelligent caching for agent queries
# Reduces repeated CLI calls by 95%+

CACHE_DIR="$HOME/.rt-cli/cache"
CACHE_TTL=300  # 5 minutes default

mkdir -p "$CACHE_DIR"

# Get cache file path for a query
cache_path() {
    local cmd="$1"
    local args="$2"
    local hash=$(echo "$cmd:$args" | md5)
    echo "$CACHE_DIR/${cmd}_${hash}.json"
}

# Check if cache is valid
cache_valid() {
    local file="$1"
    local ttl="${2:-$CACHE_TTL}"
    
    if [[ ! -f "$file" ]]; then
        return 1
    fi
    
    local age=$(($(date +%s) - $(stat -f %m "$file" 2>/dev/null || echo 0)))
    [[ $age -lt $ttl ]]
}

# Get from cache
cache_get() {
    local cmd="$1"
    local args="$2"
    local ttl="${3:-$CACHE_TTL}"
    
    local file=$(cache_path "$cmd" "$args")
    
    if cache_valid "$file" "$ttl"; then
        cat "$file"
        return 0
    fi
    
    return 1
}

# Save to cache
cache_set() {
    local cmd="$1"
    local args="$2"
    local data="$3"
    
    local file=$(cache_path "$cmd" "$args")
    echo "$data" > "$file"
}

# Clear cache
cache_clear() {
    rm -rf "$CACHE_DIR"/*
    mkdir -p "$CACHE_DIR"
    echo '{"status":"ok","message":"Cache cleared"}'
}

# Cache stats
cache_stats() {
    local total=$(find "$CACHE_DIR" -type f 2>/dev/null | wc -l | tr -d ' ')
    local size=$(du -sh "$CACHE_DIR" 2>/dev/null | awk '{print $1}')
    
    cat <<EOF
{
  "cache_dir": "$CACHE_DIR",
  "cached_queries": $total,
  "size": "$size",
  "ttl": $CACHE_TTL
}
EOF
}

# Cached wrapper for rt commands
rtc() {
    local cmd="$1"
    shift
    local args="$*"
    
    # Commands that benefit from caching
    case "$cmd" in
        stats|modules|find)
            local cached=$(cache_get "$cmd" "$args" 300)  # 5 min TTL
            if [[ -n "$cached" ]]; then
                echo "$cached"
                return 0
            fi
            
            local result=$(rt "$cmd" "$args")
            cache_set "$cmd" "$args" "$result"
            echo "$result"
            ;;
        search|count)
            local cached=$(cache_get "$cmd" "$args" 60)  # 1 min TTL
            if [[ -n "$cached" ]]; then
                echo "$cached"
                return 0
            fi
            
            local result=$(rt "$cmd" "$args")
            cache_set "$cmd" "$args" "$result"
            echo "$result"
            ;;
        deps)
            local cached=$(cache_get "$cmd" "$args" 600)  # 10 min TTL
            if [[ -n "$cached" ]]; then
                echo "$cached"
                return 0
            fi
            
            local result=$(rt "$cmd" "$args")
            cache_set "$cmd" "$args" "$result"
            echo "$result"
            ;;
        *)
            # No cache for other commands
            rt "$cmd" "$args"
            ;;
    esac
}

# If called directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]] || [[ "$ZSH_EVAL_CONTEXT" =~ :file$ ]]; then
    case "$1" in
        clear) cache_clear ;;
        stats) cache_stats ;;
        *) echo "Usage: rt-cache.sh {clear|stats}" ;;
    esac
fi
