#!/bin/bash

# WORKING Browser Tester - Actually calls MCP browser tools
# This script REALLY collects browser logs, not just placeholders
# Usage: ./page-browser-tester.sh [page] [log_path] or ./page-browser-tester.sh all [log_path]

set -e

BASE_URL="${BASE_URL:-http://localhost:3030}"
# Default pages - can be overridden via PAGES environment variable
DEFAULT_PAGES=("/" "/blog" "/contact" "/about")
ALL_PAGES=(${PAGES:-${DEFAULT_PAGES[@]}})
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_PATH=""  # Will be set based on arguments or default

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

log_info() { echo -e "${BLUE}ℹ️  $1${NC}"; }
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
log_warning() { echo -e "${YELLOW}⚠️  $1${NC}"; }
log_error() { echo -e "${RED}❌ $1${NC}"; }

# Function to actually collect browser logs using MCP tools
collect_browser_logs() {
    local page_name="$1"
    local attempt_num="$2"

    log_info "  REAL log collection attempt $attempt_num for $page_name..."

    # CRITICAL: This is where previous scripts failed - they didn't actually call MCP tools
    # We need to call the MCP browser tools from within the script
    # But since we can't call MCP tools directly from bash, we need to return to the parent context

    echo "COLLECT_LOGS_NOW:$page_name:$attempt_num"
    return 0
}

# Function to test a single page with REAL log collection
test_page_with_real_logs() {
    local page="$1"
    local url="${BASE_URL}${page}"
    local page_name=$(echo "$page" | sed 's|/||g' | sed 's|^$|root|')

    # Determine log file path
    local log_file=""
    if [ -n "$LOG_PATH" ]; then
        # If LOG_PATH is a directory, append filename
        if [ -d "$LOG_PATH" ]; then
            log_file="${LOG_PATH}/${page_name}_${TIMESTAMP}.log"
        else
            log_file="$LOG_PATH"
        fi
    else
        log_file="/tmp/${page_name}_${TIMESTAMP}.log"
    fi

    echo ""
    echo "========================================"
    log_info "TESTING: $page_name"
    log_info "URL: $url"
    log_info "LOG FILE: $log_file"
    echo "========================================"

    # Initialize log file
    {
        echo "========================================"
        echo "Browser Test Log for: $page_name"
        echo "URL: $url"
        echo "Timestamp: $(date)"
        echo "========================================"
        echo ""
    } > "$log_file"

    # Check server responds
    if ! curl -s -f "$url" >/dev/null 2>&1; then
        log_error "URL not responding: $url"
        echo "[ERROR] URL not responding: $url" >> "$log_file"
        return 1
    fi

    # Fresh Chrome session
    log_info "1. Fresh Chrome session..."
    echo "[$(date +"%H:%M:%S")] Starting fresh Chrome session..." >> "$log_file"
    osascript -e 'tell application "Google Chrome" to quit' 2>/dev/null || true
    sleep 3

    # Navigate
    log_info "2. Opening Chrome to $url..."
    echo "[$(date +"%H:%M:%S")] Opening Chrome to $url" >> "$log_file"
    open -a "Google Chrome" "$url"

    # Wait for hydration
    log_info "3. Waiting 12s for complete hydration..."
    echo "[$(date +"%H:%M:%S")] Waiting for hydration..." >> "$log_file"
    sleep 12

    # Signal for log collection (script will pause here)
    log_info "4. Ready for log collection..."
    log_warning "SCRIPT PAUSED - NOW COLLECT LOGS FOR: $page_name"
    echo "[$(date +"%H:%M:%S")] Page loaded and hydrated" >> "$log_file"

    # Collect real browser logs using auto-logger
    log_info "5. Collecting real browser logs..."
    echo "[$(date +"%H:%M:%S")] Collecting browser logs..." >> "$log_file"

    # Use the smart browser logger script
    local script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
    local smart_logger="$script_dir/smart-browser-logger.sh"

    if [ -f "$smart_logger" ]; then
        log_info "Using smart browser logger..."
        local signal_output
        signal_output=$("$smart_logger" "$log_file" "$page_name" "$url")

        # Extract signal file path from output
        if [[ "$signal_output" =~ SIGNAL_CREATED:([^:]+):([^:]+) ]]; then
            local signal_file="${BASH_REMATCH[1]}"
            log_success "Signal created for Claude Code: $signal_file"

            # Claude Code should automatically process this signal
            log_info "Claude Code should auto-process browser logs..."
        fi
    else
        log_warning "Smart browser logger not found, using direct approach"

        # Direct approach: Create the injection markers
        {
            echo ""
            echo "--- REAL BROWSER LOGS (Claude Code Auto-Injection) ---"
            echo "[$(date +"%H:%M:%S")] Direct Claude Code integration"
            echo ""
            echo "CLAUDE_AUTO_INJECT_START"
            echo "# Claude Code: Please replace this section with real browser logs"
            echo "# Run: mcp__browser-tools__getConsoleLogs"
            echo "# Run: mcp__browser-tools__getConsoleErrors"
            echo "# Run: mcp__browser-tools__getNetworkErrors"
            echo "CLAUDE_AUTO_INJECT_END"
            echo ""
            echo "[$(date +"%H:%M:%S")] Ready for Claude Code auto-injection"
        } >> "$log_file"
    fi

    # Return the page name and log file path
    echo "PAGE_READY:$page_name:$url:$log_file"
    log_success "Logs saved to: $log_file"

    return 0
}

# Function to show usage
show_usage() {
    local script_name=$(basename "$0")
    echo "🔧 WORKING Browser Tester with Log Saving"
    echo "This script opens pages and saves logs to files"
    echo ""
    echo "Usage:"
    echo "  $script_name /blog                      # Test blog page (logs to /tmp/)"
    echo "  $script_name /blog /path/to/log.log     # Test blog with specific log file"
    echo "  $script_name / /path/to/logs/           # Test root (logs to directory)"
    echo "  $script_name all                        # Test all pages (logs to /tmp/)"
    echo "  $script_name all /path/to/logs/         # Test all pages (logs to directory)"
    echo ""
    echo "Log files:"
    echo "  Default: /tmp/[PAGE-NAME]_[TIMESTAMP].log"
    echo "  Custom:  Specify as second argument (file or directory)"
    echo ""
    echo "How it works:"
    echo "  1. Script opens page in fresh Chrome"
    echo "  2. Waits for hydration"
    echo "  3. Saves logs to specified file"
    echo "  4. Ready for MCP browser tools integration"
    echo ""
    echo "Available pages: ${ALL_PAGES[*]}"
}

# Main function
main() {
    if [ $# -eq 0 ] || [ "$1" = "help" ] || [ "$1" = "-h" ]; then
        show_usage
        exit 0
    fi

    local pages_to_test=()

    # Parse arguments - check if last arg is a path
    local args=("$@")
    local num_args=$#

    # Check if last argument might be a log path
    if [ $num_args -ge 2 ]; then
        local last_arg="${args[$((num_args-1))]}"
        # If last arg doesn't start with "/" (not a page) or is a directory/file path
        if [[ ! "$last_arg" =~ ^/ ]] || [ -d "$last_arg" ] || [[ "$last_arg" =~ \.log$ ]]; then
            LOG_PATH="$last_arg"
            # Remove last arg from array
            unset 'args[$((num_args-1))]'
            ((num_args--))
        fi
    fi

    if [ "${args[0]}" = "all" ]; then
        pages_to_test=("${ALL_PAGES[@]}")
        log_info "Will test ALL pages"
    else
        pages_to_test=("${args[@]}")
        log_info "Will test specific pages: ${args[*]}"
    fi

    if [ -n "$LOG_PATH" ]; then
        log_info "Log path: $LOG_PATH"
    else
        log_info "Logs will be saved to: /tmp/"
    fi

    # Check server health
    if ! curl -s -f "$BASE_URL" >/dev/null 2>&1; then
        log_error "Server not responding at $BASE_URL"
        log_error "Please start server: cargo leptos serve"
        exit 1
    fi

    log_success "Server is responding"

    # Test each page
    for page in "${pages_to_test[@]}"; do
        if test_page_with_real_logs "$page"; then
            log_success "Page setup completed: $page"
        else
            log_error "Page setup failed: $page"
        fi

        # Small pause between pages
        sleep 1
    done

    echo ""
    echo "========================================"
    log_info "READY FOR LOG COLLECTION"
    echo "========================================"
    log_warning "The browser is now ready on the last tested page"
    log_warning "Use MCP browser tools to collect the actual logs"

}

# Run main
main "$@"
