#!/bin/bash

# Auto-Inject Browser Logs
# Automatically collects browser logs via Claude Code MCP tools
# Usage: ./auto-inject.sh <page> <log-file>

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <page> <log-file>"
    echo "Examples:"
    echo "  $0 / browser-log-root.log"
    echo "  $0 /contact browser-log-contact.log"
    exit 1
fi

PAGE="$1"
LOG_FILE="$2"
BASE_URL="http://localhost:3030"

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

echo -e "${BLUE}🤖 Auto-Inject Browser Logs${NC}"
echo -e "${BLUE}Page: $PAGE${NC}"
echo -e "${BLUE}URL: $BASE_URL$PAGE${NC}"
echo -e "${BLUE}Log file: $LOG_FILE${NC}"
echo ""

# Check if log file exists
if [ ! -f "$LOG_FILE" ]; then
    echo "❌ Log file not found: $LOG_FILE"
    exit 1
fi

# Open browser
echo -e "${BLUE}🌐 Opening Chrome...${NC}"
osascript -e "
tell application \"Google Chrome\"
    if not (exists window 1) then
        make new window
    end if
    set URL of active tab of window 1 to \"$BASE_URL$PAGE\"
    activate
end tell
" 2>/dev/null || {
    echo "❌ Failed to open Chrome"
    exit 1
}

# Wait for hydration
echo -e "${BLUE}⏳ Waiting for hydration (8 seconds)...${NC}"
sleep 8

# Create signal for Claude Code MCP injection
echo -e "${YELLOW}🔧 Creating MCP injection signal...${NC}"

# Add placeholder sections that Claude Code will replace
cat >> "$LOG_FILE" << EOF

--- AUTOMATIC MCP INJECTION ---

CLAUDE_MCP_INJECT_START
# Claude Code: Replace this section with real MCP browser logs
# Page: $PAGE
# Timestamp: $(date)
# Commands to run:
#   mcp__browser-tools__getConsoleLogs
#   mcp__browser-tools__getConsoleErrors
#   mcp__browser-tools__getNetworkErrors
CLAUDE_MCP_INJECT_END

[$(date '+%H:%M:%S')] Ready for Claude Code MCP injection
EOF

echo -e "${GREEN}✅ Signal created in: $LOG_FILE${NC}"
echo -e "${YELLOW}🤖 Claude Code will now detect and inject real MCP data${NC}"
echo -e "${BLUE}💡 Check the log file for injected browser logs${NC}"
