#!/bin/bash

# Automatic MCP Browser Log Injection Script
# This script is called by the system to inject real MCP browser logs
# Usage: ./auto-mcp-inject.sh <log-directory>

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <log-directory>"
    echo "Example: $0 browser-logs-20250806_034835"
    exit 1
fi

LOG_DIR="$1"

if [ ! -d "$LOG_DIR" ]; then
    echo "❌ Directory not found: $LOG_DIR"
    exit 1
fi

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${BLUE}🤖 Auto-MCP Injection Starting...${NC}"
echo -e "${BLUE}Directory: $LOG_DIR${NC}"
echo ""

# Find all log files that need MCP injection
log_files=($(find "$LOG_DIR" -name "*.log" -type f))

if [ ${#log_files[@]} -eq 0 ]; then
    echo "❌ No .log files found in $LOG_DIR"
    exit 1
fi

echo -e "${BLUE}📋 Found ${#log_files[@]} log files to process${NC}"

# Process each log file
for log_file in "${log_files[@]}"; do
    echo -e "${YELLOW}🔍 Processing $(basename "$log_file")...${NC}"

    # Check if file needs injection
    if grep -q "CLAUDE CODE: Please replace this section" "$log_file" 2>/dev/null; then
        echo -e "${BLUE}   📝 File needs MCP injection${NC}"

        # Create a marker file to signal Claude Code
        marker_file="${log_file}.mcp_request"
        echo "REQUEST_MCP_INJECTION" > "$marker_file"
        echo "LOG_FILE=$log_file" >> "$marker_file"
        echo "TIMESTAMP=$(date)" >> "$marker_file"

        echo -e "${GREEN}   ✅ MCP request created: $(basename "$marker_file")${NC}"
    else
        echo -e "${GREEN}   ✅ File already has real data${NC}"
    fi
done

echo ""
echo -e "${YELLOW}🤖 MCP injection requests created${NC}"
echo -e "${BLUE}💡 System should now automatically inject real browser logs${NC}"
echo ""
echo -e "${GREEN}✅ Auto-MCP injection preparation complete${NC}"
