#!/bin/bash

# Debug MapGeo integration
# Usage: ./scripts/debug-mapgeo-integration.sh

source .env

echo "=== Debugging MapGeo Integration ==="

# First, deploy the debug version
echo "Deploying debug version..."
scripts/deploy.sh staging 2>&1 | tail -n 5

echo -e "\n=== Triggering page load to generate debug output ==="
curl -s -o /dev/null https://upskill-staging.measurequick.com/find-a-trainer/
sleep 2

echo -e "\n=== Checking debug output ==="
ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" << 'ENDSSH'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Save original WP_DEBUG settings before modifying
ORIG_WP_DEBUG=$(wp config get WP_DEBUG --raw 2>/dev/null || echo "false")
ORIG_WP_DEBUG_LOG=$(wp config get WP_DEBUG_LOG --raw 2>/dev/null || echo "false")

echo "Saving original settings: WP_DEBUG=$ORIG_WP_DEBUG, WP_DEBUG_LOG=$ORIG_WP_DEBUG_LOG"

# Enable debug logging temporarily
wp config set WP_DEBUG true --raw
wp config set WP_DEBUG_LOG true --raw
wp config set WP_DEBUG_DISPLAY false --raw

# Clear any old debug log
> wp-content/debug.log

# Load the page to trigger the filter
curl -s -o /dev/null http://localhost/find-a-trainer/

# Wait a moment for log to be written
sleep 1

# Check the debug log for our MapGeo debug output
echo "=== MapGeo Debug Output ==="
grep "HVAC MapGeo Debug" wp-content/debug.log 2>/dev/null || echo "No MapGeo debug output found"

# Also check for any MapGeo-related errors
echo -e "\n=== MapGeo Related Errors ==="
grep -i "mapgeo\|igm_" wp-content/debug.log 2>/dev/null | head -n 20 || echo "No MapGeo errors found"

# Check if MapGeo plugin is active
echo -e "\n=== MapGeo Plugin Status ==="
wp plugin list | grep -i geo || echo "No geo/map plugins found"

# Check what filters are registered for igm_add_meta
echo -e "\n=== Checking registered filters ==="
wp eval '
global $wp_filter;
if (isset($wp_filter["igm_add_meta"])) {
    echo "Filters registered for igm_add_meta:\n";
    foreach ($wp_filter["igm_add_meta"] as $priority => $callbacks) {
        echo "  Priority $priority:\n";
        foreach ($callbacks as $id => $callback) {
            if (is_array($callback["function"])) {
                $class = is_object($callback["function"][0]) ? get_class($callback["function"][0]) : $callback["function"][0];
                echo "    - " . $class . "::" . $callback["function"][1] . " (accepts " . $callback["accepted_args"] . " args)\n";
            } else {
                echo "    - " . $callback["function"] . " (accepts " . $callback["accepted_args"] . " args)\n";
            }
        }
    }
} else {
    echo "No filters registered for igm_add_meta\n";
}
'

# Restore original WP_DEBUG settings
echo -e "\n=== Restoring original WP_DEBUG settings ==="
wp config set WP_DEBUG "$ORIG_WP_DEBUG" --raw
wp config set WP_DEBUG_LOG "$ORIG_WP_DEBUG_LOG" --raw
echo "Restored: WP_DEBUG=$ORIG_WP_DEBUG, WP_DEBUG_LOG=$ORIG_WP_DEBUG_LOG"

ENDSSH

echo -e "\n=== Debug Complete ==="