#!/bin/bash
# dev-test.sh — Start Forge test instance (port 4000, data ~/.forge-test)
#
# Usage:
#   ./dev-test.sh                                            # plain start
#   ./dev-test.sh --enterprise-key=fortinet:github_pat_xxx       # + persist enterprise key(s)
#   ./dev-test.sh --enterprise-key=fortinet:p1 --enterprise-key=acme:p2

set -e

mkdir -p ~/.forge-test

# Persist any --enterprise-key=... args BEFORE next dev starts so the
# server boots with sources already wired. forge-server.mjs's
# --add-enterprise-key mode is a one-shot persist + exit.
ENT_KEYS=()
for arg in "$@"; do
  case "$arg" in
    --enterprise-key=*) ENT_KEYS+=("$arg") ;;
  esac
done

if [ ${#ENT_KEYS[@]} -gt 0 ]; then
  echo "[dev-test] Registering ${#ENT_KEYS[@]} enterprise key(s) → ~/.forge-test/.enterprise-keys.json"
  node bin/forge-server.mjs --add-enterprise-key "${ENT_KEYS[@]}" --dir ~/.forge-test
fi

# All standalones default to 84xx ports (matching production). dev-test
# overrides every one so it can coexist with a real Forge on 8403.
PORT=4000 \
  TERMINAL_PORT=4001 \
  WORKSPACE_PORT=4005 \
  MCP_PORT=4006 \
  BRIDGE_PORT=4007 \
  CHAT_PORT=4008 \
  MEMORY_PORT=4009 \
  FORGE_DATA_DIR=~/.forge-test \
  FORGE_EXTERNAL_SERVICES=0 \
  npx next dev --turbopack -p 4000
