#!/usr/bin/env bash
# User-level diagnostic for the preview.rankwizai.com 500.
# Run as the app's owner user (e.g. rankwiz) from project root:
#   bash scripts/debug/as-user.sh
# Writes storage/app/debug-onboarding-500-user-<ts>.txt
#
# READ-ONLY: extends run-all.sh with Redis session inspection,
# server-side loopback curl tests, and incognito-equivalent reproduction.

set -u

cd "$(dirname "$0")/../.." || exit 1
PROJECT_ROOT="$(pwd)"
SCRIPT_DIR="$PROJECT_ROOT/scripts/debug"

if [[ ! -f "$PROJECT_ROOT/artisan" ]]; then
    echo "ERROR: not in a Laravel project root (no ./artisan at $PROJECT_ROOT)"
    exit 1
fi

if [[ $EUID -eq 0 ]]; then
    echo "WARNING: running as root. Switch to the app's owner user (e.g. rankwiz)."
    echo "Continuing anyway in 3s..."
    sleep 3
fi

DOMAIN="${DEBUG_DOMAIN:-preview.rankwizai.com}"
TS=$(date -u +%Y-%m-%dT%H-%M-%SZ)
ARTIFACT="$PROJECT_ROOT/storage/app/debug-onboarding-500-user-${TS}.txt"
mkdir -p "$(dirname "$ARTIFACT")"

# Allow override via env vars
export DEBUG_SITE_ID="${DEBUG_SITE_ID:-1}"
export DEBUG_USER_EMAIL="${DEBUG_USER_EMAIL:-}"
export DEBUG_SESSION_COOKIE="${DEBUG_SESSION_COOKIE:-}"

{
echo "================================================================"
echo "  User-level diagnostic — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "  Project root: $PROJECT_ROOT"
echo "  Domain:       $DOMAIN"
echo "  Hostname:     $(hostname)"
echo "  User:         $(whoami)"
echo "  DEBUG_SITE_ID=$DEBUG_SITE_ID"
echo "  DEBUG_USER_EMAIL=${DEBUG_USER_EMAIL:-<auto>}"
echo "  DEBUG_SESSION_COOKIE=${DEBUG_SESSION_COOKIE:+(set, $(echo -n "$DEBUG_SESSION_COOKIE" | wc -c) chars)}"
echo "================================================================"

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  [U1-U4] Standard checks (env, logs, CLI repro, share() probe)"
echo "================================================================"
echo "Delegating to run-all.sh..."
echo ""
bash "$SCRIPT_DIR/run-all.sh" 2>&1
echo ""

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  [U5] Redis session store inspection"
echo "================================================================"
php -d display_errors=1 -r '
require "vendor/autoload.php";
$app = require "bootstrap/app.php";
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

if (config("session.driver") !== "redis") {
    echo "session.driver=" . config("session.driver") . " (not redis — skipping)\n";
    exit;
}

try {
    $store = app("redis");
    $conn = $store->connection(config("session.connection") ?: "default");
    $prefix = config("cache.prefix") . ":" . (config("session.cookie") ?: "laravel_session");
    echo "session.connection: " . (config("session.connection") ?: "default") . "\n";
    echo "session.cookie:     " . config("session.cookie") . "\n";
    echo "cache.prefix:       " . config("cache.prefix") . "\n";
    echo "expected key prefix: " . $prefix . "\n";
    echo "\n";

    $candidates = [
        $prefix . ":*",
        config("cache.prefix") . "*session*",
        "*session*",
        "*",
    ];

    foreach ($candidates as $pat) {
        try {
            $keys = $conn->keys($pat);
            echo "scan pattern [" . $pat . "]: " . count($keys) . " keys\n";
            if (count($keys) > 0 && count($keys) <= 5) {
                foreach (array_slice($keys, 0, 5) as $k) echo "  - $k\n";
            } elseif (count($keys) > 5) {
                foreach (array_slice($keys, 0, 3) as $k) echo "  - $k\n";
                echo "  ... (" . (count($keys) - 3) . " more)\n";
            }
            if (count($keys) > 0) break;
        } catch (\Throwable $e) {
            echo "  scan failed: " . $e->getMessage() . "\n";
        }
    }
    echo "\n";

    if (!empty($keys)) {
        $sampleKey = $keys[0];
        $val = $conn->get($sampleKey);
        echo "Sample session ($sampleKey):\n";
        echo "  size: " . strlen($val) . " bytes\n";
        echo "  first 50 bytes: " . substr($val, 0, 50) . "\n";

        // Try to detect format
        if (substr($val, 0, 1) === "a" || substr($val, 0, 1) === "O") {
            echo "  format: PHP serialize\n";
        } elseif (substr($val, 0, 1) === "{") {
            echo "  format: JSON\n";
        } else {
            echo "  format: opaque (encrypted? see session.encrypt config)\n";
        }

        // Try unserializing — IF this fails, that is your bug
        echo "\n";
        echo "Unserialize test:\n";
        $prev = error_reporting(0);
        $unser = @unserialize($val);
        error_reporting($prev);
        if ($unser === false && $val !== "b:0;") {
            echo "  *** unserialize FAILED — session may be corrupt or encrypted ***\n";
            echo "  *** if this is the cause, deleting the user session fixes it: ***\n";
            echo "  redis-cli DEL " . $sampleKey . "\n";
        } else {
            echo "  unserialize OK (" . gettype($unser) . ")\n";
            if (is_array($unser)) {
                echo "  keys: " . implode(", ", array_keys($unser)) . "\n";
            }
        }
    }
} catch (\Throwable $e) {
    echo "ERROR inspecting Redis sessions: " . $e::class . ": " . $e->getMessage() . "\n";
    echo "  file: " . $e->getFile() . ":" . $e->getLine() . "\n";
}
' 2>&1
echo ""

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  [U6] Server-side curl loopback tests"
echo "================================================================"
echo "Hitting the real https endpoint from the server itself."
echo "If these reproduce the 500, the bug is reachable without a browser."
echo ""

echo "--- 6a. UNAUTHENTICATED hard refresh (expected: 302 to /login) ---"
curl -sk -D - "https://$DOMAIN/sites/1/onboarding" \
     -H 'Cookie:' \
     -m 15 \
     -o /tmp/curl-unauth-body.html \
     -w "\n--- meta ---\nhttp_code=%{http_code}\nelapsed=%{time_total}s\nsize=%{size_download}\n" 2>&1 \
     | head -25
echo ""
if [ -f /tmp/curl-unauth-body.html ]; then
    echo "Body first 20 lines:"
    head -20 /tmp/curl-unauth-body.html
    rm -f /tmp/curl-unauth-body.html
fi

echo ""
echo "--- 6b. UNAUTHENTICATED Inertia XHR (expected: 302) ---"
curl -sk -D - "https://$DOMAIN/sites/1/onboarding" \
     -H 'Cookie:' \
     -H 'X-Inertia: true' \
     -H 'X-Inertia-Version: dummy' \
     -H 'Accept: text/html, application/xhtml+xml' \
     -m 15 \
     -o /tmp/curl-xhr-body.html \
     -w "\n--- meta ---\nhttp_code=%{http_code}\nelapsed=%{time_total}s\nsize=%{size_download}\n" 2>&1 \
     | head -20
rm -f /tmp/curl-xhr-body.html

if [ -n "$DEBUG_SESSION_COOKIE" ]; then
    echo ""
    echo "--- 6c. AUTHED hard refresh with provided session cookie ---"
    echo "(this is what your browser actually does when 500-ing)"
    curl -sk -D - "https://$DOMAIN/sites/1/onboarding" \
         -H "Cookie: $DEBUG_SESSION_COOKIE" \
         -m 30 \
         -o /tmp/curl-authed-body.html \
         -w "\n--- meta ---\nhttp_code=%{http_code}\nelapsed=%{time_total}s\nsize=%{size_download}\n" 2>&1 \
         | head -30
    if [ -f /tmp/curl-authed-body.html ]; then
        echo ""
        echo "Body first 50 lines:"
        head -50 /tmp/curl-authed-body.html
        echo ""
        echo "--- grep for exception/error markers ---"
        grep -iE 'exception|fatal|error|laravel|whoops|stack trace|allowed memory|preview\.rankwizai' /tmp/curl-authed-body.html | head -20
        rm -f /tmp/curl-authed-body.html
    fi
else
    echo ""
    echo "--- 6c. SKIPPED — DEBUG_SESSION_COOKIE not set ---"
    echo ""
    echo "To reproduce the AUTHED 500 from the server, capture your session cookie:"
    echo "  1. Browser DevTools -> Application -> Cookies for preview.rankwizai.com"
    echo "  2. Copy the value of 'rankwizai_session' (and 'XSRF-TOKEN' if present)"
    echo "  3. Re-run with:"
    echo "     DEBUG_SESSION_COOKIE='rankwizai_session=<value>; XSRF-TOKEN=<value>' \\"
    echo "       bash scripts/debug/as-user.sh"
fi

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  [U7] Effective web SAPI php settings (best-effort from CLI)"
echo "================================================================"
echo "NOTE: web SAPI may have different ini values than CLI. The root"
echo "script ([R3]) inspects the actual web/php-fpm php.ini directly."
echo ""
php -r '
$keys = ["memory_limit","max_execution_time","display_errors","log_errors",
         "error_log","session.save_handler","session.gc_divisor","session.gc_maxlifetime",
         "session.serialize_handler","opcache.enable","opcache.validate_timestamps",
         "opcache.revalidate_freq","date.timezone"];
echo "[CLI php.ini values for reference — web SAPI may differ]\n";
foreach ($keys as $k) printf("  %-32s = %s\n", $k, ini_get($k));
'

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  [U8] Redis general health"
echo "================================================================"
php -r '
require "vendor/autoload.php";
$app = require "bootstrap/app.php";
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
try {
    $r = app("redis")->connection();
    echo "redis ping: " . $r->ping() . "\n";
    $info = $r->info("server");
    if (is_array($info)) {
        echo "redis_version: " . ($info["redis_version"] ?? "?") . "\n";
        echo "uptime_in_seconds: " . ($info["uptime_in_seconds"] ?? "?") . "\n";
    }
    $mem = $r->info("memory");
    if (is_array($mem)) {
        echo "used_memory_human: " . ($mem["used_memory_human"] ?? "?") . "\n";
        echo "maxmemory_human: " . ($mem["maxmemory_human"] ?? "?") . "\n";
    }
} catch (\Throwable $e) {
    echo "ERROR: " . $e::class . ": " . $e->getMessage() . "\n";
}
' 2>&1

# ----------------------------------------------------------------------------
echo ""
echo "================================================================"
echo "  Done — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "  Artifact: $ARTIFACT"
echo "================================================================"
} | tee "$ARTIFACT"

echo ""
echo "Paste the contents of $ARTIFACT back."
