#!/usr/bin/env bash
# build-local.sh — Build and run neuron-web + soul-demo for local development.
#
# Mirrors the container's entrypoint.sh: both processes start together,
# soul-demo in background, neuron-web in foreground. Kill neuron-web (Ctrl-C)
# and the soul dies with it. No separate process manager. No port conflicts.
#
# Usage:
#   ./build-local.sh                  — build only (fast, leaves inline JS as-is)
#   ./build-local.sh --run            — build and start both servers
#   EXTRACT_JS=1 ./build-local.sh     — also extract inline <script> blocks
#                                       into hashed, minified, obfuscated
#                                       /assets/js/<hash>.js files. Production
#                                       deploys should always extract.

set -euo pipefail
cd "$(dirname "$0")"

NEURON_DIR="$(cd ../../neuron && pwd)"
EL_HOME="${EL_HOME:-../../foundation/el}"
BOOTSTRAP="${EL_HOME}/bootstrap.py"
RUNTIME_SRC="${EL_HOME}/el-compiler/runtime"

COMPONENTS=(nav hero pillars how_it_works inference efficiency comparison
  environmental enterprise mission local_first pricing marketplace viral
  footer styles about founding_badge terms enterprise_terms checkout safety
  gallery account)

# Optional inline-JS extraction. Off by default for fast dev iteration; the
# script is idempotent so flipping the flag on a prior tree just reuses
# previously-extracted assets and emits a complete manifest.
if [[ "${EXTRACT_JS:-0}" == "1" ]]; then
  echo "==> Extracting inline JS → src/assets/js/"
  if [ ! -x "node_modules/.bin/terser" ] || [ ! -x "node_modules/.bin/javascript-obfuscator" ]; then
    echo "    installing terser + javascript-obfuscator (no-save)..."
    npm install --no-save --silent terser javascript-obfuscator
  fi
  python3 scripts/extract-js.py
fi

echo "==> Combining El sources"
{
  for f in "${COMPONENTS[@]}"; do
    [ -f "src/${f}.el" ] && grep -hv '^[[:space:]]*from\|^[[:space:]]*import' "src/${f}.el" && echo ""
  done
  grep -v '^from\|^import' src/main.el
} > dist/main-combined.el
echo "    $(wc -l < dist/main-combined.el) lines"

echo "==> Bootstrap El → C"
python3 "${BOOTSTRAP}" dist/main-combined.el > dist/main.c

echo "==> Injecting stubs"
sed -i '' 's|#include "el_runtime.h"|#include "el_runtime.h"\nel_val_t http_get_auth(el_val_t url, el_val_t tok);\nel_val_t http_post_auth(el_val_t url, el_val_t tok, el_val_t body);\nel_val_t cwd(void);\nel_val_t color_bold(el_val_t s);\nel_val_t unix_timestamp(void);\nel_val_t gcs_write(el_val_t bucket, el_val_t object_name, el_val_t content);\nel_val_t gcs_read(el_val_t bucket, el_val_t object_name);\nel_val_t supabase_insert(el_val_t project_url, el_val_t service_key, el_val_t table, el_val_t row_json);\nel_val_t supabase_get(el_val_t project_url, el_val_t service_key, el_val_t table_and_query);\nel_val_t supabase_auth_user(el_val_t project_url, el_val_t anon_key, el_val_t user_jwt);|' dist/main.c

echo "==> Compiling neuron-web"
cc -O2 \
  -I"${RUNTIME_SRC}" \
  -o dist/neuron-web \
  dist/main.c \
  dist/web_stubs.c \
  "${RUNTIME_SRC}/el_runtime.c" \
  -lcurl -lpthread
echo "    dist/neuron-web built ok"

if [[ "${1:-}" == "--run" ]]; then
  # Load credentials
  if [ -f "$HOME/Secrets/credentials/infrastructure.env" ]; then
    set -a; source "$HOME/Secrets/credentials/infrastructure.env"; set +a
  fi

  # Get Soma key for Neuron inference
  SOMA_KEY="${NEURON_LLM_0_KEY:-$(gcloud secrets versions access latest --secret=soma-operator-key --project=neuron-785695 2>/dev/null || echo '')}"

  # Kill any leftover instances from a previous run
  pkill -f "dist/neuron-web" 2>/dev/null || true
  pkill -f "neuron/dist/soul-demo" 2>/dev/null || true
  sleep 0.5

  echo "==> Starting soul-demo on :7772"
  NEURON_LLM_0_URL="https://soma-prod-us-r4tfklscwq-uc.a.run.app/v1/chat/completions" \
  NEURON_LLM_0_KEY="$SOMA_KEY" \
  NEURON_LLM_0_FORMAT="openai" \
  NEURON_LLM_0_MODEL="neuron" \
  NEURON_LLM_1_KEY="${ANTHROPIC_API_KEY:-}" \
  NEURON_LLM_1_FORMAT="anthropic" \
  NEURON_HOME="$HOME/.neuron/engram-demo" \
  NEURON_PORT=7772 \
    "${NEURON_DIR}/dist/soul-demo" &
  SOUL_PID=$!

  echo "    soul-demo pid=$SOUL_PID — waiting for init..."
  sleep 5

  echo "==> Starting neuron-web on :3001"
  # Trap exit to also kill the soul
  trap "echo '==> Stopping...'; kill $SOUL_PID 2>/dev/null; exit 0" INT TERM

  NEURON_LLM_0_URL="https://soma-prod-us-r4tfklscwq-uc.a.run.app/v1/chat/completions" \
  NEURON_LLM_0_KEY="$SOMA_KEY" \
  NEURON_LLM_0_FORMAT="openai" \
  NEURON_LLM_0_MODEL="neuron" \
  NEURON_LLM_1_KEY="${ANTHROPIC_API_KEY:-}" \
  NEURON_LLM_1_FORMAT="anthropic" \
  STRIPE_SECRET_KEY="${STRIPE_SECRET_KEY:-}" \
  STRIPE_PUBLISHABLE_KEY="${STRIPE_PUBLISHABLE_KEY:-}" \
  STRIPE_PRICE_FOUNDING="${STRIPE_PRICE_FOUNDING:-}" \
  STRIPE_PRICE_PROFESSIONAL="${STRIPE_PRICE_PROFESSIONAL:-}" \
  STRIPE_WEBHOOK_SECRET="${STRIPE_WEBHOOK_SECRET:-}" \
  SUPABASE_SERVICE_KEY="${SUPABASE_SERVICE_KEY:-}" \
  SUPABASE_ANON_KEY="${SUPABASE_ANON_KEY:-}" \
  PORT=3001 LANDING_ROOT=./src \
    dist/neuron-web

  # neuron-web exited — clean up soul
  kill $SOUL_PID 2>/dev/null || true
fi
