#!/usr/bin/env bash
# Run the platform pipeline for a single primitive (plan-only or check-only).
#
# Usage: run_primitive_plan.sh [--check-only] <primitive-name>
#
# --check-only: offline mode (no AWS) — resolves the primitive's instance.json,
#   runs the adapter, validates the emitted Terraform structure.
# (default): requires AWS — runs terraform plan on the emitted Terraform.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

CHECK_ONLY=0
PRIMITIVE=""

for arg in "$@"; do
  case "$arg" in
    --check-only) CHECK_ONLY=1 ;;
    --*) echo "FAIL: unknown flag: $arg" >&2; exit 1 ;;
    *) PRIMITIVE="$arg" ;;
  esac
done

[ -n "$PRIMITIVE" ] || { echo "FAIL: primitive name required" >&2; exit 1; }

INSTANCE="modules/l1/$PRIMITIVE/instance.json"
[ -f "$INSTANCE" ] || { echo "FAIL: no instance.json for primitive '$PRIMITIVE'" >&2; exit 1; }

WORK="/tmp/acdl_primitive_plan_$PRIMITIVE"
rm -rf "$WORK"; mkdir -p "$WORK"

echo "=== Primitive plan: $PRIMITIVE ==="
echo ""
echo "--- Step 1: adapter compiles instance -> terraform ---"
OUT_DIR="$WORK/terraform"
python3 adapters/terraform/adapter.py "$INSTANCE" "$OUT_DIR" || { echo "FAIL: adapter failed" >&2; exit 1; }
echo "adapter: emitted $OUT_DIR/{main.tf,terraform.tf,providers.tf}"

if [ "$CHECK_ONLY" = "1" ]; then
  echo ""
  echo "--- Step 2: validate adapter output structure (offline) ---"
  python3 -c "
import json, os
d = json.load(open('$INSTANCE'))
assert d['stack']['kind'] == 'l1', f\"expected l1, got {d['stack']['kind']}\"
assert len(d['resources']) >= 1
tf_dir = '$OUT_DIR'
for f in ('main.tf', 'terraform.tf', 'providers.tf'):
    assert os.path.isfile(os.path.join(tf_dir, f)), f'{f} missing'
main = open(os.path.join(tf_dir, 'main.tf')).read()
assert len(main) > 0, 'main.tf is empty'
print(f'primitive $PRIMITIVE: adapter output OK ({len(d[\"resources\"])} resource(s))')
"
  echo ""
  echo "=== PRIMITIVE CHECK OK ($PRIMITIVE) ==="
  exit 0
fi

echo ""
echo "--- Step 2: terraform init + validate + plan ---"
cd "$OUT_DIR"
terraform init -backend=false -input=false
terraform validate
terraform plan -lock=false -input=false -out=tfplan
echo "=== PRIMITIVE PLAN OK ($PRIMITIVE) ==="