#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd -- "${script_dir}/.." && pwd)"
compiler_dir="${repo_root}/compiler"

cd "${repo_root}"
git diff --check
bash -n scripts/install.sh
bash -n scripts/render-stdlib-api-doc.sh
node --check scripts/render-stdlib-api-doc.js
node --check scripts/check-stdlib-api-tiers.js

"${repo_root}/scripts/render-stdlib-api-doc.sh"
"${repo_root}/scripts/check-stdlib-api-tiers.js"
git diff --check
if ! git diff --quiet -- docs/language/STDLIB_API.md; then
  echo "standard library API catalog changed; review and commit generated docs before release" >&2
  exit 1
fi

required_pdfs=(
  "docs/papers/SLOVO_WHITEPAPER.pdf"
  "docs/papers/SLOVO_MANIFEST.pdf"
  "docs/papers/GLAGOL_WHITEPAPER.pdf"
  "docs/papers/GLAGOL_COMPILER_MANIFEST.pdf"
)

for pdf in "${required_pdfs[@]}"; do
  if [ ! -s "${pdf}" ]; then
    echo "missing generated documentation artifact: ${pdf}" >&2
    echo "run ./scripts/render-doc-pdfs.sh and commit the result" >&2
    exit 1
  fi
done

private_text_pattern='(/home/[[:alnum:]_.-]+|sanjin[0-9]+|[0-9]{1,3}\.64\.0\.1|git\.hermeticum\.io)'

if git grep -nE "${private_text_pattern}" -- \
  README.md CONTRIBUTING.md docs scripts compiler lib examples benchmarks tests .llm; then
  echo "release gate found local/private publication text" >&2
  exit 1
fi

if command -v pdftotext >/dev/null 2>&1; then
  pdf_text_dir="$(mktemp -d)"
  trap 'rm -rf "${pdf_text_dir}"' EXIT
  for pdf in "${required_pdfs[@]}"; do
    pdftotext "${pdf}" "${pdf_text_dir}/$(basename "${pdf}").txt"
  done
  if rg -n "${private_text_pattern}" "${pdf_text_dir}"; then
    echo "release gate found local/private text inside generated PDFs" >&2
    exit 1
  fi
fi

if [ "${RENDER_DOC_PDFS:-0}" = "1" ]; then
  "${repo_root}/scripts/render-doc-pdfs.sh"
  git diff --check
  if ! git diff --quiet -- docs/papers; then
    echo "documentation PDFs changed; review and commit generated artifacts before release" >&2
    exit 1
  fi
fi

cd "${compiler_dir}"
cargo fmt --check
cargo test --test diagnostics_schema_beta13
cargo test --test benchmark_suite_catalog_beta14
cargo test --test reserved_generic_collection_beta15
cargo test --test standard_string_scanning_beta16
cargo test --test standard_json_scalar_parsing_beta17
cargo test --test standard_json_string_parsing_beta18
cargo test --test test_discovery_beta19
cargo test --test standard_string_search_trim_beta20
cargo test --test standard_json_document_scalar_parsing_beta21
cargo test --test run_manifest_beta22
cargo test --test package_workspace_discipline_beta24
# Full cargo test includes unignored integration gates such as dx_v1_7,
# beta_v2_0_0_beta_1, and beta_1_0_0.
cargo test
cargo test --test promotion_gate -- --ignored
cargo test --test binary_smoke -- --ignored
cargo test --test llvm_smoke -- --ignored

echo "release gate passed: docs, stdlib API catalog, fmt, tests, promotion, binary, and LLVM smoke checks completed"
