#!/bin/sh
# entrypoint.sh — start engram then soul, both in a single container.
#
# Engram runs as a background HTTP server on localhost:8742.
# Soul starts once engram reports healthy, with ENGRAM_URL pointing at it.
#
# Data directory /data is the PVC mount point — engram reads/writes its
# snapshot.json (and any future data files) there.

set -eu

ENGRAM_PORT="${ENGRAM_PORT:-8742}"
ENGRAM_DATA_DIR="${ENGRAM_DATA_DIR:-/data}"
ENGRAM_HEALTH_URL="http://localhost:${ENGRAM_PORT}/health"

# Ensure the data directory exists (PVC may be mounted but empty on first boot)
mkdir -p "$ENGRAM_DATA_DIR"

# Start engram in the background
echo "[entrypoint] starting engram on :${ENGRAM_PORT} data_dir=${ENGRAM_DATA_DIR}"
ENGRAM_BIND=":${ENGRAM_PORT}" \
ENGRAM_DATA_DIR="$ENGRAM_DATA_DIR" \
  /usr/local/bin/engram &

ENGRAM_PID=$!

# Wait for engram to become healthy (up to 60s; GKE Autopilot cold starts can be slow)
echo "[entrypoint] waiting for engram..."
TRIES=0
until curl -sf "$ENGRAM_HEALTH_URL" > /dev/null 2>&1; do
    TRIES=$((TRIES + 1))
    if [ "$TRIES" -ge 60 ]; then
        echo "[entrypoint] ERROR: engram did not become healthy after 60s" >&2
        kill "$ENGRAM_PID" 2>/dev/null || true
        exit 1
    fi
    sleep 1
done
echo "[entrypoint] engram ready after ${TRIES}s"

# Tune EL HTTP runtime: reduce per-call timeout 60s->10s, connect timeout 3s.
export EL_HTTP_TIMEOUT_MS="${EL_HTTP_TIMEOUT_MS:-10000}"
export EL_HTTP_CONNECT_TIMEOUT_MS="${EL_HTTP_CONNECT_TIMEOUT_MS:-3000}"

# Start soul — it takes over as PID 1's foreground process.
# SOUL_ENGRAM_PATH must NOT be set; ENGRAM_URL triggers HTTP mode.
exec /usr/local/bin/neuron
