#!/bin/bash

# Multiple Pages Browser Log Collector
# Usage: ./collect-multiple-pages.sh /,/contact,/about
# Opens each page, waits for hydration, then prompts for MCP tool usage

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <page1,page2,page3>"
    echo "Examples:"
    echo "  $0 /,/contact"
    echo "  $0 /,/contact,/about"
    echo "  $0 all  # Tests common pages"
    exit 1
fi

BASE_URL="http://localhost:3030"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_DIR="browser-logs-${TIMESTAMP}"

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

# Parse pages
if [ "$1" = "all" ]; then
    pages=("/" "/contact" "/about" "/services")
else
    IFS=',' read -ra pages <<< "$1"
fi

echo -e "${BLUE}🔍 Multiple Pages Browser Log Collection${NC}"
echo -e "${BLUE}Pages: ${pages[*]}${NC}"
echo -e "${BLUE}Base URL: $BASE_URL${NC}"
echo ""

# Check server
if ! curl -s -f "$BASE_URL" >/dev/null 2>&1; then
    echo "❌ Server not responding at $BASE_URL"
    echo "Start server: just dev"
    exit 1
fi

# Create log directory
mkdir -p "$LOG_DIR"
echo -e "${GREEN}✅ Created directory: $LOG_DIR${NC}"
echo ""

# Process each page
for i in "${!pages[@]}"; do
    page="${pages[$i]}"
    page_num=$((i + 1))
    total=${#pages[@]}
    page_name=$(echo "$page" | sed 's|/||g' | sed 's|^$|root|')
    log_file="$LOG_DIR/${page_name}.log"

    echo "[$page_num/$total] =========================================="
    echo -e "${YELLOW}🔍 Page: $page${NC}"
    echo ""

    # Open browser
    echo -e "${BLUE}🌐 Opening Chrome to: $BASE_URL$page${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"
        continue
    }

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

    # Create log file
    cat > "$log_file" << EOF
========================================
Browser Log Collection: $page_name
URL: $BASE_URL$page
Timestamp: $(date)
========================================

[$(date '+%H:%M:%S')] Browser opened
[$(date '+%H:%M:%S')] Page hydrated
[$(date '+%H:%M:%S')] Ready for MCP collection

--- MCP RESULTS ---

=== CONSOLE LOGS ===


=== CONSOLE ERRORS ===


=== NETWORK ERRORS ===

EOF

    # Create MCP injection signal for Claude Code
    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)
# Signal: READY_FOR_MCP_INJECTION_${page_name}_$(date +%s)
CLAUDE_MCP_INJECT_END

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

    echo -e "${YELLOW}🤖 Collecting real browser logs via Claude Code MCP tools...${NC}"
    echo -e "${BLUE}💡 Log file created: $log_file${NC}"

    # Short pause before next page (no manual intervention needed)
    if [ $page_num -lt $total ]; then
        echo -e "${BLUE}⏭️  Moving to next page in 3 seconds...${NC}"
        sleep 3
        echo ""
    fi
done

# Auto-inject real browser logs via Claude Code MCP tools
echo ""
echo "=========================================="
echo -e "${YELLOW}🤖 Preparing for real browser log injection...${NC}"
echo "=========================================="

# Call the injection helper script
script_dir="$(dirname "${BASH_SOURCE[0]}")"
injector_script="$script_dir/inject-real-logs.sh"

if [ -f "$injector_script" ]; then
    echo -e "${BLUE}🔍 Running log injection preparation...${NC}"
    "$injector_script" "$LOG_DIR"
    echo -e "${GREEN}✅ Injection preparation completed${NC}"
else
    echo -e "${YELLOW}⚠️  Injector script not found: $injector_script${NC}"
fi

# Signal for system to automatically inject MCP data
echo ""
echo "=== SYSTEM MCP INJECTION REQUEST ==="
echo "DIRECTORY: $LOG_DIR"
echo "REQUEST: AUTO_INJECT_BROWSER_LOGS"
echo "PAGES: ${pages[*]}"
echo "TIMESTAMP: $(date)"
echo "=================================="
echo ""

echo -e "${BLUE}⏳ Waiting for system MCP injection (10 seconds)...${NC}"
sleep 10

# Auto-analyze the logs
echo ""
echo "=========================================="
echo -e "${YELLOW}📊 Auto-analyzing collected browser logs...${NC}"
echo "=========================================="

# Get path to analyze-logs.sh script
script_dir="$(dirname "${BASH_SOURCE[0]}")"
analyze_script="$script_dir/analyze-logs.sh"

if [ -f "$analyze_script" ]; then
    echo -e "${BLUE}🔍 Running automatic log analysis...${NC}"
    echo ""

    # Run the analyzer script
    if "$analyze_script" "$LOG_DIR"; then
        echo ""
        echo -e "${GREEN}✅ Complete analysis finished!${NC}"
    else
        echo -e "${YELLOW}⚠️  Analysis completed with issues${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Analyzer script not found: $analyze_script${NC}"
    echo -e "${BLUE}💡 Run manually: ./scripts/browser-logs/analyze-logs.sh $LOG_DIR${NC}"
fi

# Final summary
echo ""
echo "=========================================="
echo -e "${GREEN}🎉 COMPLETE WORKFLOW FINISHED!${NC}"
echo "=========================================="
echo ""
echo -e "${BLUE}📁 Directory: $LOG_DIR${NC}"
echo -e "${BLUE}📊 Complete Analysis: SUMMARY.md${NC}"
echo -e "${BLUE}📋 Individual logs:${NC}"
for page in "${pages[@]}"; do
    page_name=$(echo "$page" | sed 's|/||g' | sed 's|^$|root|')
    echo -e "   ${BLUE}- ${page_name}.log${NC}"
done
echo ""
echo -e "${GREEN}✅ Ready for review! Check SUMMARY.md for complete analysis${NC}"
