#!/bin/bash

# Script per lanciare Chrome con remote debugging abilitato
# Porta: 9222
# Profilo: chrome-profile/remote-chrome (persistente)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROFILE_DIR="$SCRIPT_DIR/chrome-profiles/remote-chrome"
DEBUGGING_PORT=9222

# Crea la directory del profilo se non esiste
mkdir -p "$PROFILE_DIR"

# Funzione per trovare Chrome su macOS
find_chrome() {
    # Lista di percorsi standard per Google Chrome su macOS
    local chrome_paths=(
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        "$HOME/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    )
    
    # Prima cerca nei percorsi standard
    for path in "${chrome_paths[@]}"; do
        if [ -f "$path" ]; then
            echo "$path"
            return 0
        fi
    done
    
    # Se non trovato, usa Spotlight (mdfind) per cercare nel sistema
    local spotlight_result
    spotlight_result=$(mdfind "kMDItemCFBundleIdentifier == 'com.google.Chrome'" 2>/dev/null | head -1)
    if [ -n "$spotlight_result" ] && [ -f "$spotlight_result/Contents/MacOS/Google Chrome" ]; then
        echo "$spotlight_result/Contents/MacOS/Google Chrome"
        return 0
    fi
    
    return 1
}

# Cerca Chrome
CHROME_PATH=$(find_chrome)

# Verifica che Chrome sia stato trovato
if [ -z "$CHROME_PATH" ]; then
    echo "❌ Google Chrome non trovato!"
    echo ""
    echo "   Installa Google Chrome e riprova."
    echo "   https://www.google.com/chrome/"
    exit 1
fi

echo "🚀 Avvio Chrome con remote debugging..."
echo "   Browser: $CHROME_PATH"
echo "   Porta: $DEBUGGING_PORT"
echo "   Profilo: $PROFILE_DIR"
echo ""
echo "📡 Endpoint WebSocket: http://localhost:$DEBUGGING_PORT"
echo ""

# Lancia Chrome con remote debugging
"$CHROME_PATH" \
    --remote-debugging-port=$DEBUGGING_PORT \
    --user-data-dir="$PROFILE_DIR" \
    "$@"
