#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
DEFAULT_E2E_DIR="/home/user/Projects/Press.zone/wordpress/wp-content/.worktrees/ipz-ui-makeover/plugins/international-press-zone/tests/e2e"
E2E_DIR="${IPZ_E2E_DIR:-$DEFAULT_E2E_DIR}"
RUN_BUILD=1

usage() {
    printf 'Usage: %s [--smoke]\n' "${BASH_SOURCE[0]}" >&2
    printf '  IPZ_E2E_DIR=/path/to/tests/e2e may override the source checkout.\n' >&2
}

fail() {
    printf 'build.sh: %s\n' "$1" >&2
    exit 1
}

on_exit() {
    local status=$?
    if ((status != 0)); then
        printf 'build.sh: failed (exit %d)\n' "$status" >&2
    fi
}
trap on_exit EXIT

while (($# > 0)); do
    case "$1" in
        --smoke)
            RUN_BUILD=0
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            usage
            fail "unknown option: $1"
            ;;
    esac
    shift
done

[[ -d "$E2E_DIR" ]] || fail "E2E directory does not exist: $E2E_DIR"
[[ -r "$E2E_DIR/package.json" ]] || fail "package.json is not readable: $E2E_DIR/package.json"
[[ -r "$E2E_DIR/package-lock.json" ]] || fail "package-lock.json is not readable: $E2E_DIR/package-lock.json"
[[ -r "$SCRIPT_DIR/Dockerfile" ]] || fail "Dockerfile is not readable: $SCRIPT_DIR/Dockerfile"
command -v podman >/dev/null 2>&1 || fail "podman is required"
command -v python3 >/dev/null 2>&1 || fail "python3 is required to validate the lockfile"

# Agent sandboxes cannot create rootless Podman's pause namespace directly. The
# workstation's deck-podman shim re-executes Podman through the user manager
# when needed and passes through unchanged on a normal workstation. Prefer it
# internally so the required build command remains self-contained and fail-closed.
if [[ -n "${IPZ_PODMAN_BIN:-}" ]]; then
    PODMAN_BIN="$IPZ_PODMAN_BIN"
elif command -v deck-podman >/dev/null 2>&1; then
    PODMAN_BIN="$(command -v deck-podman)"
else
    PODMAN_BIN="$(command -v podman)"
fi
[[ -x "$PODMAN_BIN" ]] || fail "Podman runner is not executable: $PODMAN_BIN"
printf 'Podman runner: %s\n' "$PODMAN_BIN"

PLAYWRIGHT_VERSION="$(python3 - "$E2E_DIR/package.json" "$E2E_DIR/package-lock.json" <<'PY'
import json
import re
import sys

package_path, lock_path = sys.argv[1:]
with open(package_path, encoding="utf-8") as stream:
    package = json.load(stream)
with open(lock_path, encoding="utf-8") as stream:
    lock = json.load(stream)

version = package.get("devDependencies", {}).get("@playwright/test")
if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version):
    raise SystemExit("@playwright/test must be an exact semver in package.json")

packages = lock.get("packages", {})
for package_name in ("@playwright/test", "playwright", "playwright-core"):
    lock_entry = packages.get(f"node_modules/{package_name}")
    if not isinstance(lock_entry, dict) or lock_entry.get("version") != version:
        actual = lock_entry.get("version") if isinstance(lock_entry, dict) else None
        raise SystemExit(
            f"{package_name} is {actual!r} in package-lock.json, expected {version!r}"
        )

print(version)
PY
)"
IMAGE="localhost/ipz-e2e-runner:${PLAYWRIGHT_VERSION}"

printf 'Playwright version: %s\n' "$PLAYWRIGHT_VERSION"
printf 'Runner image: %s\n' "$IMAGE"

if ((RUN_BUILD)); then
    "$PODMAN_BIN" build \
        --pull=missing \
        --file "$SCRIPT_DIR/Dockerfile" \
        --build-arg "PLAYWRIGHT_VERSION=$PLAYWRIGHT_VERSION" \
        --label "org.opencontainers.image.title=IPZ Playwright E2E runner" \
        --label "org.opencontainers.image.version=$PLAYWRIGHT_VERSION" \
        --tag "$IMAGE" \
        "$E2E_DIR"
fi

VERSION_OUTPUT="$("$PODMAN_BIN" run --rm "$IMAGE" npx playwright --version)"
printf '%s\n' "$VERSION_OUTPUT"
[[ "$VERSION_OUTPUT" == *"$PLAYWRIGHT_VERSION"* ]] || fail "image reports the wrong Playwright version"

SMOKE_SCRIPT='
"use strict";

const { chromium, firefox } = require("playwright");

(async () => {
  const browsers = [
    ["chromium", chromium, { headless: true, args: ["--no-sandbox"] }],
    ["firefox", firefox, { headless: true }],
  ];

  for (const [name, browserType, launchOptions] of browsers) {
    const browser = await browserType.launch(launchOptions);
    try {
      const page = await browser.newPage();
      const expectedTitle = name + " smoke";
      await page.setContent("<html><head><title>" + expectedTitle + "</title></head><body>runner smoke</body></html>");
      const title = await page.title();
      if (title !== expectedTitle) {
        throw new Error(name + " returned unexpected title: " + title);
      }
      console.log(name + ": headless launch passed");
    } finally {
      await browser.close();
    }
  }
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
'

"$PODMAN_BIN" run --rm "$IMAGE" node -e "$SMOKE_SCRIPT"

printf 'Runner image smoke passed for Chromium and Firefox.\n'
