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

echo "[1/10] Source verification"
bash scripts/verify-project.sh

echo "[2/10] Required release artifacts"
[[ -s composer.lock ]] || die "Reviewed composer.lock is missing."
[[ -f .env ]] || die "Staging .env is missing."
[[ -f vendor/autoload.php ]] || die "Composer dependencies are not installed."
[[ -f public/index.php ]] || die "Laravel front controller is missing."

echo "[3/10] Production configuration"
grep -Eq '^APP_ENV=production$' .env || die "APP_ENV must be production."
grep -Eq '^APP_DEBUG=false$' .env || die "APP_DEBUG must be false."
grep -Eq '^APP_URL=https://' .env || die "APP_URL must use HTTPS."
grep -Eq '^APP_KEY=base64:.{20,}$' .env || die "APP_KEY is missing or invalid."
grep -Eq '^DB_CONNECTION=mysql$' .env || die "DB_CONNECTION must be mysql."
grep -Eq '^SESSION_SECURE_COOKIE=true$' .env || die "SESSION_SECURE_COOKIE=true is required."
grep -Eq '^SESSION_ENCRYPT=true$' .env || die "SESSION_ENCRYPT=true is required."

echo "[4/10] Runtime extensions"
for extension in bcmath ctype curl dom fileinfo intl mbstring openssl pdo pdo_mysql pdo_sqlite tokenizer xml zip; do
  php -m | grep -qi "^${extension}$" || die "PHP extension missing: ${extension}"
done

echo "[5/10] Dependency integrity"
composer validate --strict
composer audit --no-interaction

echo "[6/10] Laravel bootstrap and route compilation"
php artisan about
php artisan route:list --except-vendor >/tmp/ojodu-hmis-phase21-routes.txt
[[ -s /tmp/ojodu-hmis-phase21-routes.txt ]] || die "Route table is empty."

echo "[7/10] Database migration review"
php artisan migrate:status
echo "No migrations are applied automatically by this gate."

echo "[8/10] Automated feature tests"
php artisan test

echo "[9/10] Staging HTTP smoke tests"
[[ -n "${HMIS_BASE_URL:-}" ]] || die "Set HMIS_BASE_URL to the HTTPS staging URL."
[[ "$HMIS_BASE_URL" == https://* ]] || die "HMIS_BASE_URL must use HTTPS."
bash scripts/http-smoke-test.sh "$HMIS_BASE_URL"

echo "[10/10] Release-candidate result"
echo "Automated release-candidate checks passed."
echo "Clinical, finance, privacy, security, interoperability and executive sign-offs remain separate mandatory approvals."
