#!/usr/bin/env bash
#
# Run the complexity ratchet and the accessibility audit against the oldest
# supported simulator runtime before pushing.
#
# Enable once per clone:
#     git config core.hooksPath .githooks
#
# Why pre-push and not pre-commit: the suite takes around ten minutes per
# runtime. At pre-commit that blocks every commit, and a hook you routinely
# bypass with --no-verify is worse than no hook, because it trains you to ignore
# it. Pushes are far less frequent and map to the unit of work.
#
# 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 this does
# not run is not run at all, and an enforced failure on it reaches main.
#
# 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"

zero='0000000000000000000000000000000000000000'
changed=''

# 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

  changed="$changed$(git diff --name-only "$range" 2>/dev/null || true)"$'\n'
done

if [ -z "$(printf '%s' "$changed" | tr -d '[:space:]')" ]; then
  exit 0
fi

# Only pay the ~85s when something could actually change the rendered UI.
if ! printf '%s' "$changed" | grep -qE '\.(swift|xcassets|xcodeproj)|\.pbxproj|xcscheme'; 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

echo "pre-push: running accessibility audit on both runtimes (~20 min)"
echo "          skip with 'git push --no-verify'"

if ! ./Scripts/audit-a11y.sh; then
  echo
  echo "pre-push: accessibility audit failed. Push aborted." >&2
  echo "          Re-run with './Scripts/audit-a11y.sh' to see which tier and" >&2
  echo "          which screen, or bypass with 'git push --no-verify'." >&2
  exit 1
fi

# Note: findings are reported, not enforced, so a clean exit here does not mean
# zero findings — read the list above. Enforcement is controlled by
# AccessibilityAuditHarness.enforcedAuditTypes.
exit 0
