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

# Dev mode for sx_docs using the native OCaml HTTP server.
# No Docker, no Python, no Quart — just the OCaml binary.
# Caddy still handles TLS and static files on externalnet.
#
# Usage:
#   ./dev-sx-native.sh              # Start on port 8013
#   ./dev-sx-native.sh 8014         # Start on custom port
#   ./dev-sx-native.sh --build      # Rebuild OCaml binary first

PORT="${1:-8013}"
BUILD=false

if [[ "${1:-}" == "--build" ]]; then
  BUILD=true
  PORT="${2:-8013}"
fi

# Build if requested or binary doesn't exist
BIN="hosts/ocaml/_build/default/bin/sx_server.exe"
if [[ "$BUILD" == true ]] || [[ ! -f "$BIN" ]]; then
  echo "[dev-sx-native] Building OCaml binary..."
  cd hosts/ocaml && eval "$(opam env)" && dune build bin/sx_server.exe && cd ../..
  echo "[dev-sx-native] Build complete"
fi

# Set project dir so the server finds spec/, lib/, web/, sx/sx/
export SX_PROJECT_DIR="$(pwd)"

echo "[dev-sx-native] Starting OCaml HTTP server on port $PORT"
echo "[dev-sx-native] project=$SX_PROJECT_DIR"
echo "[dev-sx-native] binary=$BIN"
echo ""

exec "$BIN" --http "$PORT"
