#!/bin/bash

# VS Code Session Monitor and Restart Script
# This script monitors VS Code memory usage and session health

VSCODE_MEMORY_LIMIT=2000000  # 2GB in KB
CHECK_INTERVAL=30           # Check every 30 seconds
LOG_FILE="/tmp/vscode_monitor.log"

echo "$(date): Starting VS Code session monitor..." >> "$LOG_FILE"

monitor_vscode() {
    while true; do
        # Get VS Code process info
        VSCODE_PIDS=$(pgrep -f "code.*--type=(utility|zygote)" | head -5)
        
        if [ -n "$VSCODE_PIDS" ]; then
            TOTAL_MEMORY=0
            PROCESS_COUNT=0
            
            for pid in $VSCODE_PIDS; do
                if [ -f "/proc/$pid/status" ]; then
                    MEMORY=$(awk '/VmRSS:/ {print $2}' "/proc/$pid/status" 2>/dev/null || echo 0)
                    TOTAL_MEMORY=$((TOTAL_MEMORY + MEMORY))
                    PROCESS_COUNT=$((PROCESS_COUNT + 1))
                fi
            done
            
            echo "$(date): VS Code processes: $PROCESS_COUNT, Total memory: ${TOTAL_MEMORY}KB" >> "$LOG_FILE"
            
            # Check if memory usage is too high
            if [ "$TOTAL_MEMORY" -gt "$VSCODE_MEMORY_LIMIT" ]; then
                echo "$(date): WARNING - VS Code memory usage too high: ${TOTAL_MEMORY}KB" >> "$LOG_FILE"
                echo "$(date): Recommend restarting VS Code to prevent crashes" >> "$LOG_FILE"
                
                # Optional: Force cleanup of specific high-memory processes
                for pid in $VSCODE_PIDS; do
                    if [ -f "/proc/$pid/status" ]; then
                        MEMORY=$(awk '/VmRSS:/ {print $2}' "/proc/$pid/status" 2>/dev/null || echo 0)
                        if [ "$MEMORY" -gt 500000 ]; then  # 500MB
                            echo "$(date): High memory process (PID $pid): ${MEMORY}KB" >> "$LOG_FILE"
                        fi
                    fi
                done
            fi
            
            # Check for renderer crashes
            if grep -q "renderer process gone" ~/.config/Code/logs/*/main.log 2>/dev/null; then
                echo "$(date): Renderer crash detected - recommend restart" >> "$LOG_FILE"
            fi
        fi
        
        sleep "$CHECK_INTERVAL"
    done
}

check_session_limits() {
    echo "=== VS Code Session Limits Analysis ==="
    echo "Current system limits:"
    ulimit -a | grep -E "(processes|memory|files)"
    echo ""
    
    echo "Current VS Code processes:"
    ps aux | grep -E "(code|vscode)" | grep -v grep | wc -l
    echo ""
    
    echo "VS Code memory usage:"
    ps -o pid,ppid,pcpu,pmem,rss,args -C code | head -10
    echo ""
    
    echo "GitHub Copilot Chat requests (last 50 lines):"
    find ~/.config/Code/logs -name "*copilot*" -type f -exec tail -50 {} \; 2>/dev/null | grep -c "ccreq:"
    echo ""
    
    echo "Recent crashes:"
    grep "crashed" ~/.config/Code/logs/*/main.log 2>/dev/null | tail -5
}

# Function to clean up VS Code cache and temporary files
cleanup_vscode() {
    echo "$(date): Starting VS Code cleanup..." >> "$LOG_FILE"
    
    # Clean extension host logs
    find ~/.config/Code/logs -name "*.log" -size +10M -delete 2>/dev/null
    
    # Clean old crash dumps
    find ~/.config/Code/Crashpad -type f -mtime +7 -delete 2>/dev/null
    
    # Clean temporary MCP sockets
    find /tmp -name "mcp-*" -type d -mtime +1 -exec rm -rf {} \; 2>/dev/null
    
    echo "$(date): Cleanup completed" >> "$LOG_FILE"
}

# Main execution
case "${1:-check}" in
    "monitor")
        monitor_vscode
        ;;
    "check")
        check_session_limits
        ;;
    "cleanup")
        cleanup_vscode
        ;;
    *)
        echo "Usage: $0 {monitor|check|cleanup}"
        echo "  monitor: Start continuous monitoring"
        echo "  check:   Show current session limits and status"
        echo "  cleanup: Clean VS Code cache and logs"
        ;;
esac