#!/usr/bin/env bash
#
# Generate apps/*/.env.local files with per-worktree port offsets so multiple
# overmind stacks can run side-by-side. Each worktree also gets its own
# Postgres *database* (`superlog_<slug>`) on the shared instance so feature-
# branch migrations don't pollute main's pg ledger. ClickHouse + collector
# stay shared — data isolation there happens at project_id, not db.
#
# Run from a worktree root, e.g.:
#   ./scripts/worktree-env.sh
#
# Main repo (no worktree): writes nothing and exits 0 — the default ports are
# already correct.
#
# Caveat: changing ports breaks OAuth callbacks (Google / GitHub user OAuth,
# GitHub App install, Slack, Linear) since those redirect URLs are registered
# with localhost:5173 and localhost:4100. Use the main repo for OAuth-bound
# flows. Email + password sign-up works fine on worktree ports.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

case "$REPO_ROOT" in
  */.claude/worktrees/*) ;;
  *)
    echo "not in a worktree — nothing to do (main repo uses default ports)"
    exit 0
    ;;
esac

WT_NAME="$(basename "$REPO_ROOT")"

# Slug for use in postgres database names (alnum + underscore only).
WT_SLUG="$(printf '%s' "$WT_NAME" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/_/g; s/^_+//; s/_+$//')"
DB_NAME="superlog_${WT_SLUG}"

# Deterministic 1..9 offset bucket from the worktree name; multiply by 10 so we
# get +10/+20/.../+90. cksum is portable across macOS and Linux.
BUCKET=$(printf '%s' "$WT_NAME" | cksum | awk '{print ($1 % 9) + 1}')
OFFSET=$(( BUCKET * 10 ))

API_PORT=$(( 4100 + OFFSET ))
WEB_PORT=$(( 5173 + OFFSET ))
PROXY_PORT=$(( 4000 + OFFSET ))

echo "worktree: $WT_NAME  offset: +$OFFSET  db: $DB_NAME"
echo "  api    → http://localhost:$API_PORT"
echo "  web    → http://localhost:$WEB_PORT"
echo "  proxy  → http://localhost:$PROXY_PORT"

write_env_local() {
  local path="$1"
  local content="$2"
  printf '# Generated by scripts/worktree-env.sh — do not edit by hand.\n# Worktree: %s  Offset: +%s\n%s' "$WT_NAME" "$OFFSET" "$content" > "$path"
}

write_env_local apps/api/.env.local "$(cat <<EOF
PORT=$API_PORT
WEB_ORIGIN=http://localhost:$WEB_PORT
GATEWAY_PUBLIC_URL=http://localhost:$API_PORT
DATABASE_URL=postgres://postgres:postgres@localhost:5434/$DB_NAME
EOF
)"

write_env_local apps/web/.env.local "$(cat <<EOF
WEB_PORT=$WEB_PORT
VITE_API_URL=http://localhost:$API_PORT
EOF
)"

write_env_local apps/proxy/.env.local "$(cat <<EOF
PORT=$PROXY_PORT
DATABASE_URL=postgres://postgres:postgres@localhost:5434/$DB_NAME
EOF
)"

write_env_local apps/worker/.env.local "$(cat <<EOF
API_BASE_URL=http://localhost:$API_PORT
DATABASE_URL=postgres://postgres:postgres@localhost:5434/$DB_NAME
EOF
)"

echo "wrote apps/{api,web,proxy,worker}/.env.local"
