#!/usr/bin/env bash
# beagle-ast: dump parsed+checked AST as JSON.
#
# Usage:
#   bin/beagle-ast <source.bgl|.bclj|.bjs|.bnix|.bpy>
#
# Outputs a JSON representation of the typed AST, suitable for
# consumption by external emitters (self-hosting pipeline).

set -euo pipefail
export BEAGLE_PURITY="${BEAGLE_PURITY:-warn}"  # driftlab: era code predates the !-suffix purity discipline
source "$(dirname "$0")/_beagle-racket"

if [[ $# -ne 1 ]]; then
    echo "usage: beagle-ast <source>" >&2
    exit 2
fi

src="$1"

if [[ ! -f "$src" ]]; then
    echo "beagle-ast: source file not found: $src" >&2
    exit 1
fi

# Require by file path (not collection) so the WORKTREE's beagle-lib — which
# carries ast-json.rkt — is what loads, instead of the canonical checkout's
# collection link (which lacks it).
BEAGLE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

"$RACKET" -e "
(require (file \"$BEAGLE_ROOT/beagle-lib/private/parse.rkt\")
         (file \"$BEAGLE_ROOT/beagle-lib/private/check.rkt\")
         (file \"$BEAGLE_ROOT/beagle-lib/private/ast-json.rkt\")
         json)

(define src (vector-ref (current-command-line-arguments) 0))
(define forms (read-beagle-syntax src))
(define prog (parse-program forms #:source-path src))
(type-check! prog)
(write-json (program->json prog))
(newline)
" -- "$src"
