#!/usr/bin/env bash
# Start server + frontend in dev mode using tmux.
# Run from workdir/ — this directory is the CW workspace.
# Layout: server (left) | web (right)
# Usage: ./dev.sh [session-name]

set -e

SESSION="${1:-cw}"
WORKDIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$WORKDIR/.." && pwd)"

if ! command -v tmux &>/dev/null; then
  echo "tmux not found. Install with: brew install tmux" >&2
  exit 1
fi

if tmux has-session -t "$SESSION" 2>/dev/null; then
  echo "Session '$SESSION' already running — attaching."
  exec tmux attach-session -t "$SESSION"
fi

# Single window, split vertically: server on left, web on right
tmux new-session -d -s "$SESSION" -n dev -c "$WORKDIR"

# Left pane: server (runs from workdir/ so cw finds .cwrc here)
tmux send-keys -t "$SESSION:dev" "npx tsx watch $ROOT/apps/server/bin/cw.ts --server" Enter

# Right pane: web dev server
tmux split-window -t "$SESSION:dev" -h -c "$ROOT"
tmux send-keys    -t "$SESSION:dev" "npm run dev --workspace=apps/web" Enter

# Give server pane slightly more width (60/40 split)
tmux resize-pane -t "$SESSION:dev.left" -x "60%"

# Keep focus on server pane
tmux select-pane -t "$SESSION:dev.left"

exec tmux attach-session -t "$SESSION"
