#!/usr/bin/env bash
# Fast local check before a deploy: run the logic tests, regenerate the typed API
# client from the backend's own OpenAPI schema, then typecheck the frontend
# against it. The Docker build repeats the typecheck three minutes later; this
# takes seconds. Tests first, because they fail fastest and most usefully.
set -euo pipefail
cd "$(dirname "$0")"

../.venv-dev/bin/pytest tests -q

# The vendored BW kit is byte-identical to its source (plan accounts-2026-09 §4.1).
bash scripts/vendor-check.sh

# The app's identity is its own: no header trust, no central client. After the server's gate
# lifts, Caddy no longer strips X-Auth-User, so any client could send one; and bw_auth.py is
# the one kit file that would couple this codebase to the server it was built on.
if grep -rnE "X-Auth-User|X-Auth-Grant|import +bw_auth|bw_auth +import|\bbw_auth\." app --include='*.py' | grep -v "app/vendor/" | grep -vE "^[^:]+:[0-9]+:\s*#" ; then
  echo "check.sh: main/app must not reference X-Auth-User, X-Auth-Grant or bw_auth (see above)"; exit 1
fi

../.venv-dev/bin/python -c "
import json, pathlib, sys
sys.path.insert(0, '.')
from app.main import app
pathlib.Path('web/openapi.json').write_text(json.dumps(app.openapi()))
"
cd web
npx openapi-typescript openapi.json -o src/api/schema.ts >/dev/null
npx tsc -b --pretty false
cd ..

# Doc gates (build plan §3c). The generated maps are rewritten first, so a code change in one
# session never fails another's check over a doc it does not own; docs-check.sh then verifies
# the tree. Advisory ONLY while app/version.py lags CHANGELOG.md, a defect the gate found on
# its first run (rian bumps the version; request in .logs/decisions-for-rian.md). The moment
# they agree, a red gate is a red check, with no edit here.
../.venv-dev/bin/python scripts/docmap.py --write >/dev/null
if ! bash docs-check.sh -q; then
  ver=$(sed -nE 's/^APP_VERSION *= *"([^"]+)".*/\1/p' app/version.py)
  cl=$(grep -oE '^## [0-9]+\.[0-9]+\.[0-9]+' CHANGELOG.md | head -1 | cut -c4-)
  if [[ "$ver" != "$cl" ]]; then
    echo "doc gates: ADVISORY while app/version.py ($ver) lags CHANGELOG.md ($cl); fatal once they agree"
  else
    exit 1
  fi
fi
echo "checks passed"
