#!/usr/bin/env bash
# Path-filtered CI gate for the internal web UI (#436).
# Runs the hermetic web UI unittest suite when a change touches UI surfaces.
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/.." && pwd)"
cd "$repo_root"

if [[ "${WEBUI_CI_FORCE:-}" == "1" ]]; then
  exec "$script_dir/test-webui"
fi

base_ref="${WEBUI_CI_BASE_REF:-}"
if [[ -z "$base_ref" ]]; then
  if git rev-parse --verify prgs/master >/dev/null 2>&1; then
    base_ref="$(git merge-base HEAD prgs/master 2>/dev/null || true)"
  fi
  if [[ -z "$base_ref" ]]; then
    base_ref="${GITHUB_BASE_REF:-${CHANGE_TARGET:-master}}"
    if git rev-parse --verify "origin/$base_ref" >/dev/null 2>&1; then
      base_ref="$(git merge-base HEAD "origin/$base_ref")"
    elif git rev-parse --verify "$base_ref" >/dev/null 2>&1; then
      base_ref="$(git merge-base HEAD "$base_ref")"
    else
      base_ref="HEAD~1"
    fi
  fi
fi

changed="$(git diff --name-only "$base_ref" HEAD 2>/dev/null || true)"
if [[ -z "$changed" ]]; then
  echo "ci-webui-check: no changed files vs $base_ref; skipping web UI suite"
  exit 0
fi

python_bin="${WEBUI_TEST_PYTHON:-python3}"
if [[ -x "$repo_root/venv/bin/python" ]]; then
  python_bin="$repo_root/venv/bin/python"
fi

if printf '%s\n' "$changed" | "$python_bin" -c "
import sys
from webui.ci_paths import should_run_webui_ci
paths = [line.strip() for line in sys.stdin if line.strip()]
raise SystemExit(0 if should_run_webui_ci(paths) else 1)
"; then
  echo "ci-webui-check: web UI surface changed; running suite"
  exec "$script_dir/test-webui"
fi

echo "ci-webui-check: no web UI paths in diff; skipping suite"
exit 0