#!/bin/zsh
# Run Claude or Codex in a Deck-owned tmux session.
#
# Usage:
#   deck pair ABCDE-FGHIJ
#   deck claude [directory] [agent arguments...]
#   deck codex  [directory] [agent arguments...]
#   cct [directory] [Claude arguments...]   # compatibility shortcut
#   dct [directory] [Codex arguments...]    # compatibility shortcut
set -eu

provider="${1:-}"
case "$provider" in
  pair)
    code="${2:-}"
    [[ -n "$code" ]] || {
      print -u2 "usage: deck pair ABCDE-FGHIJ"
      exit 2
    }
    root="${${0:A}:h:h}"
    exec "$root/install.sh" --relay-url "https://deck-relay-c6b560.fly.dev" --pair "$code"
    ;;
  claude) binary="claude"; prefix="cc" ;;
  codex) binary="codex"; prefix="cx" ;;
  *)
    print -u2 "usage: deck <pair|claude|codex> [arguments...]"
    exit 2
    ;;
esac
shift

command -v "$binary" >/dev/null 2>&1 || {
  print -u2 "Deck could not find $binary on PATH."
  exit 127
}
command -v tmux >/dev/null 2>&1 || {
  print -u2 "cct, dct and deck $provider need tmux. Install it with: brew install tmux"
  exit 127
}

export TMUX_TMPDIR=/tmp
export LANG="${LANG:-en_US.UTF-8}"

dir="$PWD"
if [[ $# -ge 1 && -d "$1" ]]; then
  dir="${1:A}"
  shift
fi

base="${dir:t}"
base="${${base//[^a-zA-Z0-9_-]/-}:l}"
name="${prefix}-${base:-home}"

if [[ $# -eq 0 ]] && tmux has-session -t "=$name" 2>/dev/null; then
  if [[ -n "${TMUX:-}" ]]; then exec tmux switch-client -t "=$name"; fi
  exec tmux attach-session -t "=$name"
fi

n="$name"; i=2
while tmux has-session -t "=$n" 2>/dev/null; do
  n="${name}-$i"
  ((i++))
done

args=""
if [[ $# -gt 0 ]]; then args=" ${(j: :)${(q)@}}"; fi
if [[ -n "${TMUX:-}" ]]; then
  tmux new-session -d -s "$n" -c "$dir" -- /bin/zsh -lc "exec ${binary}${args}"
  exec tmux switch-client -t "=$n"
fi
exec tmux new-session -s "$n" -c "$dir" -- /bin/zsh -lc "exec ${binary}${args}"
