#!/usr/bin/env bash
#
# Run the complexity ratchet, and refuse a push whose tree has no recorded
# accessibility audit pass.
#
# Enable once per clone:
#     git config core.hooksPath .githooks
#
# The audit runs before the push, not here: `./Scripts/audit-a11y.sh` on a
# clean tree records the tree it passed on, and this hook looks it up. git opens
# the connection before running pre-push, and gitbay kills a push that moves no
# data for a minute or has not reached pre-receive fifteen minutes after taking
# its slot. The suite takes around twenty minutes, so run inside the hook it
# failed every push it gated.
#
# Why both tiers: audit coverage is not nested across OS versions — each runtime
# reports findings the others miss, in both directions, which
# Docs/ACCESSIBILITY.txt records per screen. There is no CI, so a tier that is
# not run is not run at all, and an enforced failure on it reaches main. Only a
# run of both tiers is recorded.
#
# Why the hook runs qlty at all: nothing else does. This repository's origin is
# gitbay, which has no build configured, so the smell gates in .qlty/qlty.toml
# are only ever evaluated by someone running them. A ratchet nobody runs holds
# nothing.
#
# Skip deliberately with: git push --no-verify

set -euo pipefail

repo_root=$(git rev-parse --show-toplevel)
cd "$repo_root"

# shellcheck source=../Scripts/lib/audit-pass.sh
source Scripts/lib/audit-pass.sh

zero='0000000000000000000000000000000000000000'
needs_audit=''

# stdin: <local ref> <local sha> <remote ref> <remote sha>, one line per ref.
while read -r _local_ref local_sha _remote_ref remote_sha; do
  [ "$local_sha" = "$zero" ] && continue  # branch deletion

  if [ "$remote_sha" = "$zero" ]; then
    # New branch: diff against the default branch rather than the whole history.
    base=$(git merge-base origin/main "$local_sha" 2>/dev/null || echo '')
    range="${base:+$base..}$local_sha"
  else
    range="$remote_sha..$local_sha"
  fi

  if git diff --name-only "$range" 2>/dev/null | grep -qE "$AUDIT_INPUTS"; then
    needs_audit="$needs_audit $local_sha"
  fi
done

if [ -z "$needs_audit" ]; then
  echo "pre-push: no Swift/project changes, skipping accessibility audit"
  exit 0
fi

qlty=''
for candidate in "$(command -v qlty || true)" "$HOME/.qlty/bin/qlty"; do
  if [ -n "$candidate" ] && [ -x "$candidate" ]; then
    qlty="$candidate"
    break
  fi
done

if [ -z "$qlty" ]; then
  echo "pre-push: qlty not found, skipping the complexity ratchet"
else
  echo "pre-push: checking the complexity ratchet"

  # Counted from SARIF rather than trusted to the exit code, which is 0 even
  # with findings — `qlty smells --quiet` reports and does not fail. Only
  # file-complexity is counted: duplication findings exist today
  # (CloudSyncService has a 15-line similar block) and are reported, not gated.
  over=$("$qlty" smells --all --sarif 2>/dev/null | python3 -c "
import json, sys
try:
    document = json.load(sys.stdin)
except Exception:
    print('unknown')
    raise SystemExit(0)
print(sum(
    1
    for run in document.get('runs', [])
    for result in run.get('results', [])
    if result.get('ruleId') == 'qlty:file-complexity'
))
")

  if [ "$over" = "unknown" ]; then
    echo "pre-push: could not read qlty output, skipping the ratchet"
  elif [ "$over" != "0" ]; then
    echo
    echo "pre-push: $over file(s) past the complexity threshold. Push aborted." >&2
    echo "          See './Scripts/../.qlty/qlty.toml'. Split the file, or lower" >&2
    echo "          the threshold deliberately — do not raise it to pass." >&2
    echo "          List them with 'qlty smells --all'." >&2
    echo "          Bypass with 'git push --no-verify'." >&2
    exit 1
  fi
fi

passes=$(audit_pass_file)
missing=''
for sha in $needs_audit; do
  grep -qxF "$(git rev-parse "$sha^{tree}")" "$passes" 2>/dev/null || missing="$missing $sha"
done

if [ -n "$missing" ]; then
  echo "pre-push: no recorded accessibility audit pass for:" >&2
  for sha in $missing; do
    echo "            $(git log -1 --format='%h %s' "$sha")" >&2
  done
  echo "          Check it out with a clean tree, run './Scripts/audit-a11y.sh'," >&2
  echo "          then push again. Bypass with 'git push --no-verify'." >&2
  exit 1
fi

echo "pre-push: accessibility audit passed on this tree"
exit 0
