#!/bin/bash

# Single Page Browser Log Collector
# Usage: ./collect-single-page.sh /contact
# Opens browser, waits for hydration, then prompts for MCP tool usage

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <page-path>"
    echo "Examples:"
    echo "  $0 /"
    echo "  $0 /contact"
    echo "  $0 /about"
    exit 1
fi

PAGE="$1"
BASE_URL="http://localhost:3030"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
PAGE_NAME=$(echo "$PAGE" | sed 's|/||g' | sed 's|^$|root|')
LOG_FILE="browser-log-${PAGE_NAME}-${TIMESTAMP}.log"

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

echo -e "${BLUE}🔍 Single Page Browser Log Collection${NC}"
echo -e "${BLUE}Page: $PAGE${NC}"
echo -e "${BLUE}URL: $BASE_URL$PAGE${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

# 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
}

echo -e "${GREEN}✅ Browser opened to: $BASE_URL$PAGE${NC}"
echo ""

# Wait for hydration
echo -e "${BLUE}⏳ Waiting for page hydration (8 seconds)...${NC}"
sleep 8
echo -e "${GREEN}✅ Page hydrated${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 ---
(Paste Claude Code MCP tool results below)

=== CONSOLE LOGS ===


=== CONSOLE ERRORS ===


=== NETWORK ERRORS ===

EOF

echo -e "${YELLOW}📋 Now run these MCP tools in Claude Code:${NC}"
echo ""
echo "   mcp__browser-tools__getConsoleLogs"
echo "   mcp__browser-tools__getConsoleErrors"
echo "   mcp__browser-tools__getNetworkErrors"
echo ""
echo -e "${GREEN}✅ Log file created: $LOG_FILE${NC}"
echo -e "${BLUE}💡 Paste MCP results into the log file${NC}"
