#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REMOTE_RUNNER="${HOME}/.claude/bin/e2e-remote"
CONTAINER="devzone-wordpress"
BUILD_BOX_REGISTRY="${HOME}/.claude/buildbox-hosts.json"

usage() {
    printf 'Usage: %s <spec-path-relative-to-tests/e2e> [extra playwright args...]\n' "$0" >&2
}

SPEC_INPUT="${1-}"
if [[ -z "$SPEC_INPUT" ]]; then
    usage
    exit 2
fi
shift

case "$SPEC_INPUT" in
    /*)
        printf '%s: spec path must be relative to tests/e2e: %s\n' "$0" "$SPEC_INPUT" >&2
        exit 2
        ;;
esac

if ! command -v realpath >/dev/null 2>&1; then
    printf '%s: realpath is required to validate the spec path\n' "$0" >&2
    exit 127
fi

SPEC_PATH="$SCRIPT_DIR/$SPEC_INPUT"
SPEC_REAL="$(realpath -e -- "$SPEC_PATH" 2>/dev/null || true)"
if [[ -z "$SPEC_REAL" || ! -f "$SPEC_REAL" || "$SPEC_REAL" != "$SCRIPT_DIR/"* ]]; then
    printf '%s: spec file not found under tests/e2e: %s\n' "$0" "$SPEC_INPUT" >&2
    exit 2
fi
SPEC="${SPEC_REAL#"$SCRIPT_DIR/"}"

if [[ ! -x "$REMOTE_RUNNER" ]]; then
    printf '%s: e2e-remote is missing or not executable: %s\n' "$0" "$REMOTE_RUNNER" >&2
    exit 127
fi

if [[ ! -r "$BUILD_BOX_REGISTRY" ]]; then
    printf '%s: buildbox registry is unavailable: %s\n' "$0" "$BUILD_BOX_REGISTRY" >&2
    exit 1
fi
HOSTS="$(node -e '
const fs = require("fs");
const registry = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const byName = new Map(registry.hosts.map((host) => [host.name, host]));
const hosts = (registry.orders?.e2e || []).filter((name) => {
    const host = byName.get(name);
    return host?.state === "reachable" && host.roles?.includes("e2e");
});
if (!hosts.length) process.exit(1);
process.stdout.write(hosts.join(","));
' "$BUILD_BOX_REGISTRY")" || {
    printf '%s: no reachable e2e buildbox in %s\n' "$0" "$BUILD_BOX_REGISTRY" >&2
    exit 1
}

if ! command -v deck-podman >/dev/null 2>&1; then
    printf '%s: deck-podman is required to discover the dev WordPress URL\n' "$0" >&2
    exit 127
fi

if ! deck-podman container exists "$CONTAINER" >/dev/null 2>&1; then
    printf '%s: WordPress container is unavailable: %s\n' "$0" "$CONTAINER" >&2
    exit 1
fi

if [[ "$(deck-podman container inspect -f '{{.State.Running}}' "$CONTAINER" 2>/dev/null)" != "true" ]]; then
    printf '%s: WordPress container is not running: %s\n' "$0" "$CONTAINER" >&2
    exit 1
fi

HOME_URL_OUTPUT=""
if ! HOME_URL_OUTPUT="$(deck-podman exec "$CONTAINER" php -r 'require "/var/www/html/wp-load.php"; echo home_url(), PHP_EOL;' 2>&1)"; then
    printf '%s: failed to discover home_url() from %s: %s\n' \
        "$0" "$CONTAINER" "${HOME_URL_OUTPUT//$'\n'/ }" >&2
    exit 1
fi

HOME_URL="${HOME_URL_OUTPUT##*$'\n'}"
HOME_URL="${HOME_URL%/}"

if [[ ! "$HOME_URL" =~ ^http://100\.126\.128\.50:8080(/[^[:space:]]*)?$ ]]; then
    printf '%s: rejecting unsafe WordPress home_url(): %s\n' "$0" "$HOME_URL" >&2
    exit 1
fi


if ! curl -fsS --max-time 15 -o /dev/null "${HOME_URL}/wp-login.php"; then
    printf '%s: WordPress is not answering at %s\n' "$0" "$HOME_URL" >&2
    exit 1
fi

PROJECT_ARGS=(--project=chromium)
for arg in "$@"; do
    if [[ "$arg" == --project=* || "$arg" == --project ]]; then
        PROJECT_ARGS=()
        break
    fi
done

cd "$SCRIPT_DIR"
exec "$REMOTE_RUNNER" \
    --hosts "$HOSTS" \
    --env "WP_BASE_URL=${HOME_URL}" \
    -- npx playwright test "$SPEC" --config playwright.config.js "${PROJECT_ARGS[@]}" "$@"
