#!/usr/bin/env bash
set -e

# pwd -P (physical): tmux reports pane paths symlink-resolved; HERE must compare
# equal to them or the reattach check below would always miss (/tmp vs /private/tmp).
HERE="$(cd "$(dirname "$0")" && pwd -P)"
source "$HERE/dojo.env.sh"

HEADLESS=0
COACHED=0
while [ $# -gt 0 ]; do
  case "$1" in
    -d|--debug|--headless) HEADLESS=1; shift;;
    --coached) COACHED=1; shift;;   # re-entry from inside the tmux wrap (below)
    -h|--help) echo "Usage: $0 [-d|--debug]"; exit 0;;
    *) echo "unknown arg: $1" >&2; exit 2;;
  esac
done

cd "$HERE"   # all file access is relative to the challenge dir; the sandbox hook enforces it

# DOJO_COACH=1 marks "this IS the real coach" so the coachguard SessionStart hook
# stays SILENT for it. Set it INLINE on each `claude` exec below — NEVER exported —
# because `exec tmux new-session` (the bootstrap further down) would otherwise bake
# it into the tmux SERVER's global env, and a plain `claude` the learner opens in a
# SIBLING pane would then wrongly inherit it and skip the "coaching is OFF" warning
# (the exact cheat the guard exists to close). The --coached re-entry re-runs this
# script inside tmux, so its own exec re-sets it.

if [ "$HEADLESS" -eq 1 ]; then
  exec env DOJO_COACH=1 claude "${DOJO_HEADLESS_ARGS[@]}" "${DOJO_BASE_ARGS[@]}" "$DOJO_TASK"
fi

# The coach conversation OUTLIVES any one window. Its session id is pinned at
# first boot (`.dojo/coach-sid` — gitignored RUNTIME state, so branch surgery on
# seals/resets never resurrects it) and a reboot of the SAME beat resumes that
# thread with `claude --resume` instead of starting over. A DIFFERENT slug in the
# file (= /next re-rendered dojo.env.sh for the next beat, or a reset re-cut this
# one) rotates to a fresh id — a new beat always gets a new coach conversation.
SIDFILE="$HERE/.dojo/coach-sid"

launch_coach() {
  sid_slug=''; sid=''
  if [ -f "$SIDFILE" ]; then
    read -r sid_slug sid < "$SIDFILE" || true
  fi
  if [ -n "$sid" ] && [ "$sid_slug" = "$DOJO_SLUG" ]; then
    # Same beat, prior conversation on disk → resume mid-thread. NO $DOJO_TASK:
    # the kickoff already lives in the transcript; re-sending would replay it.
    # A refused resume (transcript gone/corrupt) fails fast → fall through to a
    # fresh coach; a clean learner exit lands on the `exit 0` and ends the pane.
    env DOJO_COACH=1 claude --resume "$sid" "${DOJO_BASE_ARGS[@]}" && exit 0
  fi
  if command -v uuidgen >/dev/null 2>&1; then
    sid="$(uuidgen | tr '[:upper:]' '[:lower:]')"
  else
    sid="$(cat /proc/sys/kernel/random/uuid)"   # slim containers without uuidgen
  fi
  mkdir -p "$HERE/.dojo"
  printf '%s %s\n' "$DOJO_SLUG" "$sid" > "$SIDFILE"
  exec env DOJO_COACH=1 claude --session-id "$sid" "${DOJO_BASE_ARGS[@]}" "$DOJO_TASK"
}

# Second entry: we're already inside the tmux session (see the wrap below) —
# just run the coach. /check will split a live proof pane beside it.
if [ "$COACHED" -eq 1 ]; then
  launch_coach
fi

# RESUME-FIRST: a live detached `dojo` tmux session IS the coach, mid-conversation
# — tmux outlives VS Code, so after a window close / editor restart only the
# terminal VIEW died. Reattach silently (no banner, no relaunch). A leftover
# session from a DIFFERENT campaign dir is the wrong coach → kill it and boot
# fresh below (the old behavior, now scoped to actual strangers).
if [ -z "${TMUX:-}" ] && command -v tmux >/dev/null 2>&1 \
   && tmux has-session -t dojo 2>/dev/null; then
  if [ "$(tmux display-message -p -t dojo '#{pane_current_path}' 2>/dev/null)" = "$HERE" ]; then
    exec tmux -f "$HERE/dojo.tmux.conf" attach-session -t dojo
  fi
  tmux kill-session -t dojo 2>/dev/null || true
fi

if [ -t 1 ]; then
  B=$(tput bold); D=$(tput dim); R=$(tput sgr0)
  CYAN=$(tput setaf 6); MAGENTA=$(tput setaf 5)
else
  B='' D='' R='' CYAN='' MAGENTA=''
fi
RULE="${D}──────────────────────────────────────────────${R}"

cat <<BANNER

  ${RULE}
   ${B}${CYAN}Challenge ${DOJO_SLUG}${R} ${B}— ${DOJO_NAME}${R}
  ${RULE}

   Your coach is waiting inside — it explains, you act (or watch),
   and nothing advances until you're ready.

   ${D}What you build here is yours to keep.${R}

  ${B}${MAGENTA}Press Enter${R} to begin. ${D}Ctrl+C to back out.${R}

BANNER

read -r

# The proof (/check) spawns a FRESH Claude in a VISIBLE split pane the learner
# WATCHES — that needs the coach to live inside tmux so /check has a pane to
# split. Bootstrap one (loading our minimal profile so the learner's own
# ~/.tmux.conf never changes the experience). Already in tmux, or no tmux on
# PATH → run the coach directly; /check then degrades to a headless proof the
# coach relays inline.
if [ -z "${TMUX:-}" ] && command -v tmux >/dev/null 2>&1; then
  exec tmux -f "$HERE/dojo.tmux.conf" new-session -s dojo -c "$HERE" "'$HERE/run' --coached"
fi
launch_coach
