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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SESSION="${SYBIL_TMUX_SESSION:-sybil-dev}"
LOG_DIR="$ROOT/.devbox/logs"
PID_DIR="$ROOT/.devbox/pids"

require_env() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "Missing required environment variable: $name" >&2
    exit 1
  fi
}

require_env OPENAI_API_KEY
require_env EXA_API_KEY

mkdir -p "$LOG_DIR" "$PID_DIR"

export HOST="${HOST:-0.0.0.0}"
export PORT="${PORT:-8787}"
export DATABASE_URL="${DATABASE_URL:-file:$ROOT/server/dev.db}"

echo "Installing server dependencies..."
npm ci --prefix "$ROOT/server" --no-audit --no-fund

echo "Installing web dependencies..."
npm ci --prefix "$ROOT/web" --no-audit --no-fund

if command -v tmux >/dev/null 2>&1; then
  tmux kill-session -t "$SESSION" >/dev/null 2>&1 || true
  tmux new-session -d -s "$SESSION" -n server -c "$ROOT/server" "sleep infinity"
  tmux set-environment -t "$SESSION" OPENAI_API_KEY "$OPENAI_API_KEY"
  tmux set-environment -t "$SESSION" EXA_API_KEY "$EXA_API_KEY"
  tmux set-environment -t "$SESSION" HOST "$HOST"
  tmux set-environment -t "$SESSION" PORT "$PORT"
  tmux set-environment -t "$SESSION" DATABASE_URL "$DATABASE_URL"
  if [[ -n "${BRIX_CLUSTER:-}" ]]; then
    tmux set-environment -t "$SESSION" BRIX_CLUSTER "$BRIX_CLUSTER"
  fi
  for name in \
    CHAT_CODEX_TOOL_ENABLED \
    CHAT_CODEX_REMOTE_HOST \
    CHAT_CODEX_REMOTE_USER \
    CHAT_CODEX_REMOTE_PORT \
    CHAT_CODEX_REMOTE_WORKDIR \
    CHAT_CODEX_SSH_KEY_PATH \
    CHAT_CODEX_SSH_PRIVATE_KEY_B64 \
    CHAT_CODEX_EXEC_TIMEOUT_MS \
    CHAT_SHELL_TOOL_ENABLED \
    CHAT_SHELL_EXEC_TIMEOUT_MS; do
    if [[ -n "${!name:-}" ]]; then
      tmux set-environment -t "$SESSION" "$name" "${!name}"
    fi
  done
  tmux respawn-pane -k -t "$SESSION:server.0" -c "$ROOT/server" "npm run dev"
  tmux new-window -t "$SESSION" -n web -c "$ROOT/web" \
    "npm run dev -- --host 0.0.0.0 --port 5173"
  echo "Started Sybil in tmux session '$SESSION'."
  echo "Server: http://127.0.0.1:8787"
  echo "Web:    http://127.0.0.1:5173"
  exit 0
fi

echo "tmux not found; starting background processes with nohup."

if [[ -f "$PID_DIR/server.pid" ]]; then
  kill "$(cat "$PID_DIR/server.pid")" >/dev/null 2>&1 || true
fi
if [[ -f "$PID_DIR/web.pid" ]]; then
  kill "$(cat "$PID_DIR/web.pid")" >/dev/null 2>&1 || true
fi

(
  cd "$ROOT/server"
  exec env HOST="$HOST" PORT="$PORT" DATABASE_URL="$DATABASE_URL" npm run dev
) >"$LOG_DIR/server.log" 2>&1 &
echo "$!" >"$PID_DIR/server.pid"

(
  cd "$ROOT/web"
  exec npm run dev -- --host 0.0.0.0 --port 5173
) >"$LOG_DIR/web.log" 2>&1 &
echo "$!" >"$PID_DIR/web.pid"

echo "Started Sybil background processes."
echo "Server log: $LOG_DIR/server.log"
echo "Web log:    $LOG_DIR/web.log"
