#!/usr/bin/env bash
# Idempotent security-gate runtime provisioning: python3 + pytest, and the oracle detector's
# bun-resolved TypeScript compiler API (module-scoped node_modules, never committed).
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TYPESCRIPT_VERSION="5.9.3"
ORACLE_DIR="$ROOT/domains/security/detectors/oracle"

fail() {
  echo "bootstrap: $1" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || fail "required command not found: $1 ($2)"
}

# ts.ScriptTarget is undefined under the typescript@7 default export: the oracle would then run,
# emit nothing, and report a clean gate.
oracle_ts_api_ok() {
  (cd "$ORACLE_DIR" && bun -e \
    'import ts from "typescript"; if (typeof ts.ScriptTarget === "undefined" || typeof ts.createSourceFile !== "function") process.exit(1);') \
    >/dev/null 2>&1
}

need_cmd python3 "deterministic orchestrator, ledger, bench and recall gates"
need_cmd bun "oracle detector runtime (domains/security/detectors/oracle/oracle2.ts)"
need_cmd npm "module-scoped TypeScript install"

python3 -c 'import pytest' 2>/dev/null || fail "python package 'pytest' missing (check.sh gate 1); install it for python3"

if ! oracle_ts_api_ok; then
  npm install --prefix "$ROOT" --no-save "typescript@${TYPESCRIPT_VERSION}" >/dev/null \
    || fail "npm install typescript@${TYPESCRIPT_VERSION} failed under $ROOT"
  oracle_ts_api_ok || fail "typescript@${TYPESCRIPT_VERSION} installed but the compiler API is unresolvable from $ORACLE_DIR"
fi

echo "bootstrap: security runtime OK (python3 + pytest, bun + typescript@${TYPESCRIPT_VERSION})"
