#!/usr/bin/env bash
# Runs on the AI box (started by ci/run-remote.sh): every suite of `npm run check:all`, one after
# another, each in a container. Prints a summary and exits non-zero when a suite fails.
#
#   remote-check.sh <checkout dir> [<env file in /dev/shm>]
#
# KIMAAI_CI_PLAN names a plan from scripts/test-plan.mjs (`npm run check:related`): then only the steps it
# selects for the AI box run, with its filters (PHP versions, Playwright specs, WP-CLI test classes).
set -uo pipefail

DIR="$1"
ENV_FILE="${2:-}"
PLAN="${KIMAAI_CI_PLAN:-}"
cd "$DIR" || exit 1

# selected <suite>: whether a step runs (always, without a plan).
selected() {
  [ -z "$PLAN" ] && return 0
  python3 -c 'import json, sys; suite = json.load(open(sys.argv[1]))["suites"].get(sys.argv[2]); sys.exit(0 if suite and suite["where"] == "AI box" else 1)' "$PLAN" "$1"
}

# plan_filter <suite> <key>: a filter from the plan, lists space-separated; empty without a plan or filter.
plan_filter() {
  [ -z "$PLAN" ] && return 0
  python3 -c 'import json, sys; value = json.load(open(sys.argv[1]))["suites"].get(sys.argv[2], {}).get(sys.argv[3], ""); print(" ".join(value) if isinstance(value, list) else value)' "$PLAN" "$1" "$2"
}

USER_ID="$(id -u):$(id -g)"
# The run's id (the checkout's folder name) labels its containers and names its Compose projects, so an
# interrupted run can find and remove them.
RUN_ID="$(basename "$DIR")"
LABEL=(--label "kimaai-ci=$RUN_ID")
PROJECT="kimaai-ci-$RUN_ID"
PHP_VERSIONS=(8.0 8.1 8.2 8.3 8.4)
NODE_IMAGE="kimaai-ci-node"
PLAYWRIGHT_VERSION="$(python3 -c "import json; print(json.load(open('package-lock.json'))['packages']['node_modules/@playwright/test']['version'])")"
# Kept between runs, next to the checkouts.
NPM_CACHE="$(dirname "$DIR")/.cache/npm"
COMPOSER_IMAGE="composer:2.9"
# Ollama for the integration and e2e tests (the box's own by default); it takes precedence over .env.test.
OLLAMA_URL="${KIMAAI_CI_OLLAMA_URL:-http://host.docker.internal:11434/v1}"
OLLAMA_ENV=(
  -e OLLAMA_BASE_URL="$OLLAMA_URL"
  -e OLLAMA_MODEL="${KIMAAI_CI_OLLAMA_MODEL:-qwen2.5:3b}"
  -e OLLAMA_EMBED_MODEL="${KIMAAI_CI_OLLAMA_EMBED_MODEL:-nomic-embed-text:v1.5}"
)

ENV_MOUNT=()
INTEGRATION_ENV_MOUNT=()
if [ -n "$ENV_FILE" ]; then
  ENV_MOUNT=(-e KIMAAI_PAID_TESTS=1 -v "$ENV_FILE:/app/.env.test:ro")
  INTEGRATION_ENV_MOUNT=(-e KIMAAI_PAID_TESTS=1 -v "$ENV_FILE:/wp/wp-content/plugins/kimaai/.env.test:ro")
fi

mkdir -p .ci-logs "$NPM_CACHE"
RESULTS=()
FAILED=0

step() {
  local name="$1"
  shift
  local log=".ci-logs/$(echo "$name" | tr -c 'a-zA-Z0-9' '-' | cut -c1-120).log"
  local start=$SECONDS
  printf '%s ... ' "$name"
  if "$@" >"$log" 2>&1; then
    echo "ok ($((SECONDS - start))s)"
    RESULTS+=("ok      $name ($((SECONDS - start))s)")
  else
    echo "FAILED ($((SECONDS - start))s)"
    tail -n 120 "$log"
    RESULTS+=("FAILED  $name ($((SECONDS - start))s)")
    FAILED=1
  fi
}

node_run() {
  docker run --rm "${LABEL[@]}" --user "$USER_ID" --ipc=host -e HOME=/tmp/home -e CI=1 -e npm_config_cache=/npm-cache -v "$NPM_CACHE:/npm-cache" \
    --add-host=host.docker.internal:host-gateway "${OLLAMA_ENV[@]}" \
    -v "$DIR:/app" ${ENV_MOUNT[@]+"${ENV_MOUNT[@]}"} -w /app "$NODE_IMAGE" bash -c "$1"
}

# PHPCS finds the project's own sniffs (Sniffs/, "KimaAI.*") through the checkout's folder name.
php_run() {
  docker run --rm "${LABEL[@]}" --user "$USER_ID" -v "$DIR:/kimaai" -w /kimaai "php:$1-cli" sh -c "$2"
}

# The integration bootstrap expects the plugin inside a WordPress tree for the CA bundle path; the bundle
# comes from the PHP image, so this works on the box and on a Mac alike.
#
#   integration_run <PHP version>
integration_run() {
  mkdir -p "$DIR/.ci-ca"
  docker run --rm "${LABEL[@]}" php:8.4-cli cat /etc/ssl/certs/ca-certificates.crt >"$DIR/.ci-ca/ca-bundle.crt" || return 1
  docker run --rm "${LABEL[@]}" --user "$USER_ID" --add-host=host.docker.internal:host-gateway "${OLLAMA_ENV[@]}" \
    -v "$DIR:/wp/wp-content/plugins/kimaai" \
    ${INTEGRATION_ENV_MOUNT[@]+"${INTEGRATION_ENV_MOUNT[@]}"} \
    -v "$DIR/.ci-ca:/wp/wp-includes/certificates:ro" \
    -w /wp/wp-content/plugins/kimaai "php:$1-cli" \
    sh -c 'vendor/bin/phpunit --config=phpunit.integration.xml'
}

compose() {
  PLUGIN_DIR="$DIR/.ci-plugin/kimaai" docker compose -p "$PROJECT" -f "$DIR/ci/docker-compose.yml" "$@"
}

# The WP-CLI commands against a real WordPress (tests/cli): PHPUnit in the cli service, with the checkout as
# the plugin and premium forced on as in e2e, Qdrant as the vector store and Ollama for the embeddings.
# The free plugin is staged (dev vendor) for the free-build test.
#
#   cli_tests [<WordPress image> <WP-CLI image>]   (default: the latest WordPress on PHP 8.3)
cli_tests() {
  local status=1
  local -x WP_IMAGE="${1:-}" CLI_IMAGE="${2:-}"
  local filter=()
  [ -n "$CLI_CLASSES" ] && filter=(--filter "/\\b(${CLI_CLASSES// /|})::/")
  node_run "node ci/stage-free-plugin.mjs /app /app/.ci-plugin/kimaai" || return 1
  if cli_compose up -d --wait db wordpress qdrant; then
    cli_compose run --rm "${OLLAMA_ENV[@]}" -e QDRANT_URL=http://qdrant:6333 \
      -e KIMAAI_CLI_FREE_PLUGIN=/var/www/html/wp-content/plugins/kimaai/.ci-plugin/kimaai \
      -w /var/www/html/wp-content/plugins/kimaai cli vendor/bin/phpunit --config=phpunit.cli.xml ${filter[@]+"${filter[@]}"}
    status=$?
  fi
  cli_compose down -v --remove-orphans
  return $status
}

cli_compose() {
  PLUGIN_DIR="$DIR" docker compose -p "$PROJECT-cli" -f "$DIR/ci/docker-compose.yml" "$@"
}

# Plugin Check runs on what the free plugin ships, and fails on every error that is not in
# ci/plugin-check-baseline.txt (empty since QA-8).
plugin_check() {
  docker run --rm "${LABEL[@]}" --user "$USER_ID" -e COMPOSER_HOME=/tmp/composer -v "$DIR:/app" -w /app "$COMPOSER_IMAGE" \
    composer install --no-dev --optimize-autoloader --no-interaction --no-progress || return 1
  node_run "node ci/stage-free-plugin.mjs /app /app/.ci-plugin/kimaai" || return 1
  compose up -d --wait db wordpress || return 1
  compose run --rm cli wp core install --url=http://localhost --title=CI --admin_user=admin \
    --admin_password=admin --admin_email=ci@example.com --skip-email || return 1
  compose run --rm cli wp plugin install plugin-check --activate || return 1
  compose run --rm cli wp plugin activate kimaai || return 1
  compose run --rm cli wp plugin check kimaai --format=csv --ignore-warnings \
    --require=./wp-content/plugins/plugin-check/cli.php >.ci-logs/plugin-check.csv || return 1
  python3 ci/plugin-check-compare.py .ci-logs/plugin-check.csv ci/plugin-check-baseline.txt .ci-logs/plugin-check-errors.txt
}

# Stops this run and removes everything it left on the box: its containers, Compose projects and volumes, the
# checkout and the env file with the API keys.
stop_run() {
  kill -TERM "$$" 2>/dev/null
  local ids
  ids="$(for label in "kimaai-ci=$RUN_ID" "com.docker.compose.project=$PROJECT" "com.docker.compose.project=$PROJECT-cli"; do
    docker ps -aq --filter "label=$label"
  done)"
  [ -n "$ids" ] && docker rm -f $ids
  compose down -v --remove-orphans
  cli_compose down -v --remove-orphans
  rm -rf "$DIR"
  [ -n "$ENV_FILE" ] && rm -f "$ENV_FILE"
}

# ci/run-remote.sh sends a line every two seconds on stdin. When that stops (Ctrl-C, a dropped connection), the
# watcher stops the run instead of leaving it running on the box.
WATCHER=""
if [ "${KIMAAI_CI_WATCH:-0}" = 1 ]; then
  exec 3<&0 </dev/null
  (
    while IFS= read -r -t 120 _ <&3; do :; done
    stop_run
  ) >/dev/null 2>&1 &
  WATCHER=$!
fi

UNIT_PHP="$(plan_filter unit php)"
INTEGRATION_PHP="$(plan_filter integration php)"
E2E_SPECS="$(plan_filter e2e specs)"
CLI_CLASSES="$(plan_filter cli classes)"

if [ -n "$PLAN" ]; then
  echo "check:related on $(hostname) in $DIR"
else
  echo "check:all on $(hostname) in $DIR"
fi
[ -n "$ENV_FILE" ] && echo "Real-provider tests: on (.env.test)" || echo "Real-provider tests: off"

NODE=0
NPM=0
OLLAMA=0
for suite in build eslint stylelint jest storybook e2e; do selected "$suite" && NPM=1; done
for suite in cli pluginCheck; do selected "$suite" && NODE=1; done
for suite in integration e2e cli; do selected "$suite" && OLLAMA=1; done
[ "$NPM" = 1 ] && NODE=1
# The Ollama check runs in the Node image too.
[ "$OLLAMA" = 1 ] && NODE=1

[ "$NODE" = 1 ] && step "Node image" docker build -q -t "$NODE_IMAGE" --build-arg PLAYWRIGHT_VERSION="$PLAYWRIGHT_VERSION" -f ci/node.Dockerfile ci
# Without Ollama the Ollama tests would only skip; fail instead, so a run never passes without them.
[ "$OLLAMA" = 1 ] && step "Ollama reachable ($OLLAMA_URL)" node_run 'curl -fsS --max-time 10 "$OLLAMA_BASE_URL/models" >/dev/null'
[ "$NPM" = 1 ] && step "npm ci" node_run "npm ci --no-audit --no-fund"
{ selected build || selected e2e; } && step "Build" node_run "npx npm-run-all build:wp build:admin-tailwind"
selected eslint && step "ESLint" node_run "npm run lint:js"
selected stylelint && step "Stylelint" node_run "npm run lint:css"
selected jest && step "Jest" node_run "npm run test:js"
selected storybook && step "Storybook build" node_run "npm run build:storybook"
selected composer && step "Composer validate" docker run --rm "${LABEL[@]}" --user "$USER_ID" -v "$DIR:/app" -w /app "$COMPOSER_IMAGE" composer validate --strict
selected phpcs && step "PHPCS" php_run 8.4 "vendor/bin/phpcs -s --tab-width=2 --standard=phpcs.ruleset.xml"
selected phpstan && step "PHPStan" php_run 8.4 "vendor/bin/phpstan analyse --configuration=phpstan.neon --memory-limit=1G"
if selected unit; then
  for version in ${UNIT_PHP:-${PHP_VERSIONS[*]}}; do
    step "PHPUnit unit (PHP $version)" php_run "$version" "vendor/bin/phpunit --config=phpunit.xml"
  done
fi
# The oldest and the newest PHP the plugin supports.
if selected integration; then
  for version in ${INTEGRATION_PHP:-8.0 8.4}; do
    step "PHPUnit integration (PHP $version)" integration_run "$version"
  done
fi
# The free plugin is staged for tests/e2e/specs/free-build.spec.ts. A plan may name the specs to run.
selected e2e && step "Playwright e2e${E2E_SPECS:+ (specs: $(echo "$E2E_SPECS" | wc -w | tr -d ' '))}" \
  node_run "node ci/stage-free-plugin.mjs /app /app/.ci-plugin/kimaai && KIMAAI_E2E_FREE_PLUGIN=/app/.ci-plugin/kimaai npm run test:e2e${E2E_SPECS:+ -- $E2E_SPECS}"
selected cli && step "WP-CLI (Docker WordPress)${CLI_CLASSES:+ ($CLI_CLASSES)}" cli_tests
# Opt-in (`npm run check:all -- --wp-min`, about 3 minutes more): the oldest WordPress and PHP the plugin supports.
if [ "${KIMAAI_CI_WP_MIN:-0}" = 1 ] && selected cli; then
  # No official 6.6 image runs PHP 8.0; the tests run in the PHP 8.0 CLI container, the web server on 8.1.
  step "WP-CLI (WordPress 6.6, PHP 8.0)" cli_tests wordpress:6.6-php8.1-apache wordpress:cli-php8.0
fi
# Last: it replaces the dev vendor with the production one.
selected pluginCheck && step "Plugin Check" plugin_check
compose down -v --remove-orphans >/dev/null 2>&1
[ -n "$WATCHER" ] && kill "$WATCHER" 2>/dev/null

echo
echo "Summary ($(git -C "$DIR" log -1 --format=%h 2>/dev/null || basename "$DIR"))"
printf '  %s\n' "${RESULTS[@]}"
exit "$FAILED"
