#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
die(){ echo "PHASE 20 ACCEPTANCE BLOCKED: $*" >&2; exit 1; }

echo "[1/8] Static source verification"
bash scripts/verify-project.sh

echo "[2/8] Runtime prerequisites"
[[ -s composer.lock ]] || die "composer.lock is missing. Generate, review and commit it."
[[ -f vendor/autoload.php ]] || die "Composer dependencies are not installed."
[[ -f .env ]] || die ".env is missing; prepare a staging environment."
command -v composer >/dev/null 2>&1 || die "Composer is unavailable."
php -m | grep -qi '^pdo_sqlite$' || die "PDO SQLite is required for the configured feature test suite."
php -m | grep -qi '^pdo_mysql$' || die "PDO MySQL is required for staging database acceptance."

echo "[3/8] Composer metadata and dependency security"
composer validate --strict
composer audit --no-interaction

echo "[4/8] Laravel boot and route compilation"
php artisan about
php artisan route:list --except-vendor >/tmp/ojodu-hmis-routes.txt
test -s /tmp/ojodu-hmis-routes.txt

echo "[5/8] Database migration status (read-only)"
php artisan migrate:status

echo "[6/8] Feature acceptance tests"
php artisan test

echo "[7/8] Optional HTTP smoke tests"
if [[ -n "${HMIS_BASE_URL:-}" ]]; then
  bash scripts/http-smoke-test.sh "$HMIS_BASE_URL"
else
  echo "HMIS_BASE_URL not supplied: public HTTP smoke test skipped."
fi

echo "[8/8] Acceptance summary"
echo "Automated acceptance checks completed. This does not replace clinical sign-off, privacy/DPIA approval, penetration testing, FHIR/DHIS2 conformance or disaster-recovery drills."
