#!/usr/bin/env bash
#
# spellcheck - run the CI cspell gate locally, faithfully. agora_theme's copy.
#
# PROVENANCE. Copied from the Ágora Transparency site template under D-028 and ADAPTED;
# tests/bin/shared-invariants.manifest records it as `adapted` with the source commit it
# was taken from. It is NOT one of D-028's four shared invariants - those are no-secrets,
# no-patches, no-blind-phpunit and identity-strings. This is a local PRE-FLIGHT: nothing
# in the gate runner executes it, because it needs the network and pnpm, and `cspell` is
# already its own blocking job in the pipeline. It is here so that a human can see the
# job's verdict before the push rather than after it.
#
# WHY IT WAS COPIED AT ALL, given D-028 does not name it. In the site template the local
# pre-flight was this:
#
#     pnpm dlx cspell@9.8.0 --locale en,en-GB README.md "specs/**/*.md"
#
# advertised as an approximation. It was worse than that: with no .cspell.json in the
# repository, that command loads NO project dictionary and NONE of Drupal core's, so it
# disagreed with the gate in both directions at once - hundreds of false positives hiding
# the handful of real ones. Three consecutive pipelines went red on cspell (934242, 934297,
# 934329) while the local check reported the same noise it always reported. That is I-051,
# and I-034 in its purest form: a signal nobody could read stopped being a signal at all.
#
# THIS repository's cspell job is blocking from its FIRST pipeline (_ALL_VALIDATE_ALLOW_FAILURE
# is '0' in .gitlab-ci.yml). Arriving with the usable pre-flight already in place, instead of
# learning the same lesson a second time at the same cost, is the entire reason this file is
# in T-508's deliverables.
#
# WHAT IT DOES. It reproduces what the cspell job actually runs, by fetching the same
# inputs rather than guessing them:
#
#   * gitlab_templates' assets/.cspell.json          - the base config the job copies in
#   * Drupal core's core/misc/cspell/*.txt           - the two dictionaries the job registers
#   * .cspell-project-words.txt                      - this project's own, per _CSPELL_DICTIONARY
#
# and then applies, in this script, the transformations scripts/prepare-cspell.php applies
# in the job: the extra word list, the ignorePaths, and the fifteen built-in dictionaries.
#
# ONE adaptation of substance, and it is not cosmetic. prepare-cspell.php line 93 derives
# allowed words from `explode('_', CI_PROJECT_NAME)` and then merges in the parts of every
# *.info.yml filename it finds. For `agora_transparency` that yields agora + transparency;
# here CI_PROJECT_NAME is `agora_theme` and the info file is `agora_theme.info.yml`, so it
# yields agora + theme. Carrying the template's word list over unchanged would have allowed
# a word this project's job does not allow, and disallowed one it does - a pre-flight that
# disagrees with the gate in both directions is the exact failure described above.
#
# WHAT IT IS STILL NOT. It is a replica, not the job. It pins nothing about the runner's
# node version, and prepare-cspell.php can change upstream without this file noticing.
# It was verified equivalent in the site template on 2026-08-24 against pipeline 934329:
# same verdict, and after the fix, 64 files checked and 0 issues - the same denominator the
# job reported. NO such comparison has been made for THIS repository yet, and cannot be: it
# has never run a pipeline. The first equivalence check here is T-507's job, against the
# first observed `cspell` job. Until then this script's denominator is a claim about what
# cspell opened locally and nothing more. (I-045: a green linter is a statement about the
# set it opened, so this script always prints the set.)
#
# Usage:  bash tests/bin/spellcheck [--refresh]
#         --refresh  re-fetch the upstream inputs even if the cache is warm.

set -u

# `pwd -W` is what makes this work under Git Bash on Windows: the shell reports /c/Users/...
# but node, python and cspell all want C:/Users/... . Passing the MSYS form to them produced
# 68 "file not found" lines and a run over zero files that still printed "Issues found: 0" -
# I-028 exactly, the degenerate case and the expected value wearing the same words.
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && { pwd -W 2>/dev/null || pwd; })"
cd "$REPO" || { echo "FATAL: cannot cd to repository root"; exit 2; }

CACHE="$REPO/.cspell-cache"
CSPELL_VERSION="9.8.0"
UPSTREAM_CONFIG="https://git.drupalcode.org/project/gitlab_templates/-/raw/main/assets/.cspell.json"
# WHICH BRANCH THE DICTIONARIES COME FROM, AND WHY IT IS NOT 11.x.
#
# This used to fetch core's cspell dictionaries from the 11.x DEVELOPMENT branch, and that made
# the local check MORE PERMISSIVE THAN THE GATE. Measured on 2026-08-25: `vincentlanglet` is in
# 11.x's dictionary.txt and is NOT in 11.4.x's. The theme's README cited that package name, the
# local run reported "30 files checked, 0 issues", and the blocking CI job then failed on it.
#
# CI installs DRUPAL_CORE=$CORE_STABLE, which is 11.4.5 - so the dictionaries it reads are the
# ones on the 11.4.x branch. A pre-flight that reads a newer, larger dictionary silently accepts
# words the gate will reject, which is the exact failure I-051 names: a local check that models
# most of a gate is not the gate, and the half it does not model is where something gets through.
#
# Update this when the project moves to a newer stable core - and note that pointing it back at
# 11.x would not look like a mistake, it would look like an upgrade.
CORE_BRANCH="11.4.x"
CORE_DICT="https://git.drupalcode.org/project/drupal/-/raw/$CORE_BRANCH/core/misc/cspell/dictionary.txt"
DRUPAL_DICT="https://git.drupalcode.org/project/drupal/-/raw/$CORE_BRANCH/core/misc/cspell/drupal-dictionary.txt"

REFRESH=0
[ "${1:-}" = "--refresh" ] && REFRESH=1

fail() { echo "FATAL: $*" >&2; exit 2; }

command -v curl   >/dev/null 2>&1 || fail "curl not found"
command -v python3 >/dev/null 2>&1 || fail "python3 not found"
command -v pnpm   >/dev/null 2>&1 || fail "pnpm not found - it is the only package manager this project uses"

mkdir -p "$CACHE" || fail "cannot create $CACHE"

# ---------------------------------------------------------------- fetch the upstream inputs
fetch() {
  local url="$1" dest="$2" name="$3"
  if [ "$REFRESH" -eq 0 ] && [ -s "$dest" ]; then
    echo "  cached   $name"
    return 0
  fi
  local code
  code="$(curl -sS -o "$dest.tmp" -w '%{http_code}' "$url" 2>/dev/null)"
  if [ "$code" != "200" ]; then
    rm -f "$dest.tmp"
    # A stale cache is worth more than nothing, but say so out loud.
    if [ -s "$dest" ]; then
      echo "  STALE    $name (HTTP $code; using the cached copy - the result may lag the job)"
      return 0
    fi
    fail "cannot fetch $name (HTTP $code) and there is no cached copy. Offline? The gate cannot be reproduced without it."
  fi
  mv "$dest.tmp" "$dest"
  echo "  fetched  $name"
}

# ---------------------------------------------------------------- the parity check
# WHY THIS EXISTS, and it is the reason the branch above is not just a corrected constant.
#
# Three times in one day a local pre-flight disagreed with the gate it models: phpcs (comment
# lines only, characters not bytes), stylelint (CI symlinks core's .prettierrc.json first), and
# this script (core dictionaries read from the development branch). The first two were NOISIER
# than the gate, which is annoying. This one was QUIETER, which is dangerous - a pre-flight that
# accepts what the gate rejects does not merely fail to help, it actively certifies a red push.
#
# So the branch is no longer trusted as a constant. It is CHECKED against the value the pipeline
# actually uses, read at source from gitlab_templates:
#   CORE_STABLE, in includes/include.drupalci.hidden-variables.yml, is what DRUPAL_CORE resolves
#   to, and the dictionaries live on that release's branch (11.4.5 -> 11.4.x).
#
# When Drupal releases a new stable minor, THIS SAYS SO AND STOPS, instead of going quiet and
# certifying words the gate will reject. Being told is the whole point: a silent divergence is
# what cost the theme a red pipeline.
UPSTREAM_HIDDEN="https://git.drupalcode.org/project/gitlab_templates/-/raw/main/includes/include.drupalci.hidden-variables.yml"
CORE_STABLE="$(curl -sS "$UPSTREAM_HIDDEN" 2>/dev/null | sed -n "s/^[[:space:]]*CORE_STABLE:[[:space:]]*.\([0-9.]*\).*/\1/p" | head -1)"
if [ -z "$CORE_STABLE" ]; then
  echo "  UNVERIFIED  could not read CORE_STABLE upstream - the dictionary branch is UNCHECKED this run"
  echo "              (offline, or the variables file moved. The result may be quieter than the gate.)"
else
  EXPECTED_BRANCH="$(echo "$CORE_STABLE" | cut -d. -f1,2).x"
  if [ "$EXPECTED_BRANCH" = "$CORE_BRANCH" ]; then
    echo "  parity    CORE_STABLE=$CORE_STABLE upstream -> dictionaries on $EXPECTED_BRANCH, which is what this script reads"
  else
    echo "FATAL: this pre-flight would be QUIETER THAN THE GATE." >&2
    echo "  upstream CORE_STABLE = $CORE_STABLE, so CI reads core's dictionaries from $EXPECTED_BRANCH." >&2
    echo "  this script reads    $CORE_BRANCH." >&2
    echo "  A newer dictionary accepts words the blocking cspell job rejects, and a run that says" >&2
    echo "  \"0 issues\" would then be certifying a red push. Set CORE_BRANCH=$EXPECTED_BRANCH and" >&2
    echo "  re-run with --refresh so the cached dictionaries are re-fetched from it." >&2
    exit 2
  fi
fi
echo "upstream inputs (core dictionaries from branch $CORE_BRANCH - the branch CI installs)"
fetch "$UPSTREAM_CONFIG" "$CACHE/upstream.cspell.json" "gitlab_templates assets/.cspell.json"
fetch "$CORE_DICT"       "$CACHE/dictionary.txt"        "Drupal core dictionary.txt"
fetch "$DRUPAL_DICT"     "$CACHE/drupal-dictionary.txt" "Drupal core drupal-dictionary.txt"
[ -f "$REPO/.cspell-project-words.txt" ] || fail ".cspell-project-words.txt is missing - the job registers it via _CSPELL_DICTIONARY"

# ---------------------------------------------------------------- build the effective config
python3 - "$REPO" "$CACHE" <<'PY' || fail "could not build the effective config"
import json, os, sys
repo, cache = sys.argv[1].replace(os.sep, "/"), sys.argv[2].replace(os.sep, "/")
c = json.load(open(os.path.join(cache, "upstream.cspell.json"), encoding="utf-8"))
# prepare-cspell.php: words it merges in unconditionally, plus the project's name parts.
c["words"] = ["agora", "theme", "lando", "ddev", "endapply", "nightwatchjs", "testgroup",
  "testgroups", "backlinks", "mdhash", "uploaders", "vocabs", "curlopt", "returntransfer", "curle",
  "customrequest", "failonerror", "postfields", "followlocation", "colourdefinitionsniff",
  "seletorsingleline", "teamplatespacingaftercomment", "tforvalue", "trhowscommentindentation",
  "unecessaryfiledeclaration", "blocklisted", "flagwords", "mkdocs", "autorun"]
# prepare-cspell.php: non-project directories, always-ignored files, and the standard set.
c["ignorePaths"] = ["web", "vendor", "node_modules", ".git", "recipes", ".cspell-cache",
  "*.patch", "*.svg", "*_ignore_*", "build.env", "get-file-via-curl.sh",
  "_cspell_unrecognized_words.txt", "_cspell_updated_project_words.txt",
  "**/.*.json", "package.json", "yarn.lock", "phpstan*", ".*ignore",
  "LICENSE.txt", "composer.json", "composer.lock"]
c["globRoot"] = repo
c["dictionaryDefinitions"] = [
  {"name": "drupal",        "path": cache + "/drupal-dictionary.txt"},
  {"name": "dictionary",    "path": cache + "/dictionary.txt"},
  {"name": "project-words", "path": repo + "/.cspell-project-words.txt"}]
c["dictionaries"] = ["companies", "fonts", "html", "php", "softwareTerms", "misc", "typescript",
  "node", "css", "bash", "filetypes", "npm", "lorem-ipsum", "sql", "fullstack",
  "drupal", "dictionary", "project-words"]
json.dump(c, open(os.path.join(cache, "effective.cspell.json"), "w", encoding="utf-8"), indent=2)
PY

# ---------------------------------------------------------------- the file set
# Tracked AND untracked-but-not-ignored: a file that is about to be committed is a file the
# job will read, and the whole point of a pre-flight is to see it before the push does.
git ls-files --cached --others --exclude-standard \
  | sed "s#^#$REPO/#" > "$CACHE/files.txt" || fail "git ls-files failed"
COUNT="$(wc -l < "$CACHE/files.txt" | tr -d ' \r')"
echo
echo "file set: $COUNT tracked or stage-able files offered to cspell"
echo "          (it will skip a few by the upstream ignorePaths above and say how many)"
echo

# ---------------------------------------------------------------- run it
pnpm dlx "cspell@$CSPELL_VERSION" \
  --config "$CACHE/effective.cspell.json" \
  --locale en,en-GB \
  --no-progress \
  --file-list "$CACHE/files.txt"
RC=$?

echo
if [ "$RC" -eq 0 ]; then
  echo "spellcheck: clean - and the line above states over how many files, which is the half"
  echo "            that makes it a gate rather than a badge (I-045)."
else
  echo "spellcheck: FAILED. Every word above is one of four things (D-024(3)):"
  echo "  * a real misspelling                 -> fix the prose"
  echo "  * British English                    -> already covered by --locale en,en-GB; if it is"
  echo "                                          still flagged it is not the spelling you think"
  echo "  * project vocabulary or a proper noun-> .cspell-project-words.txt, ONE justified line each"
  echo "  * a verbatim quotation               -> scope it in the file with cspell:disable/enable,"
  echo "                                          or cspell:ignore for a long quoted passage"
  echo "  Copying the job's _cspell_updated_project_words.txt over the word list is forbidden:"
  echo "  it is one command from a green pipeline and it declares the next real misspelling correct."
fi
exit "$RC"
