#!/usr/bin/env bash
# Output: JSON with additionalContext (for Claude) and systemMessage (shown to the owner on the startup screen).
# Set LANE_PLAIN=1 to get the plain text instead (used by the wrapper for terminal printing).
if [ -z "${LANE_PLAIN:-}" ] && [ -z "${_LANE_INNER:-}" ]; then
  input=""; [ -t 0 ] || input=$(cat)
  text=$(printf '%s' "$input" | _LANE_INNER=1 "$0" "$@")
  screen=$(printf '%s' "$input" | _LANE_INNER=1 LANE_SCREEN=1 "$0" "$@")
  python3 -c 'import json,sys; ctx,scr=sys.argv[1],sys.argv[2]; print(json.dumps({"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":ctx},"systemMessage":scr}))' "$text" "$screen"
  exit 0
fi
# SessionStart hook. Reads the hook JSON on stdin (session_id, transcript_path, source, cwd), prints
# context for Claude: the board, the dispatcher procedure, and — for resumed conversations — which repo
# the conversation belongs to and the exact choices to offer the owner before anything else.
source "$(python3 -c 'import os,sys;print(os.path.dirname(os.path.realpath(sys.argv[1])))' "$0")/lib.sh"
source "$PRODUCT/scripts/gitstate.sh"
input=""; [ -t 0 ] || input=$(cat)
printf '%s' "$input" > "$CACHE_DIR/last-session-start.json" 2>/dev/null || true
read -r source sid scwd <<<"$(printf '%s' "$input" | python3 -c 'import json,sys
try: d=json.load(sys.stdin)
except Exception: d={}
print(d.get("source","startup"), d.get("session_id","-"), d.get("cwd","-"))' 2>/dev/null || echo "startup - -")"
[ "$scwd" = "-" ] && scwd="$PWD"
# repo the conversation belongs to: the managed-repo project folder that holds <session_id>.jsonl
# (transcript_path in the hook input is derived from cwd, not from where the file lives — do not use it)
repo=""
if [ "$sid" != "-" ]; then
  # the project folder is named after THIS folder's path, so compute it rather than assume it
  # (a mirror's folder is named after repos/<repo>, which sits under .repolane/ in a workspace)
  slug=$(claude_project_dir "$REPOS")
  f=$(ls "$HOME"/.claude/projects/"$slug"-*/"$sid".jsonl 2>/dev/null | head -1 || true)
  [ -n "$f" ] && { repo=${f#*"$slug"-}; repo=${repo%%/*}; }
fi
# How a session runs the lane-* commands and names the data folders: a workspace's package puts the commands on PATH, so
# they go by name, and the data sits under .repolane/; a clone's are its scripts/ folder, by absolute path.
if [ "$LANE_MODE" = workspace ]; then X=""; else X="$PRODUCT/scripts/"; fi
MEM_REL="${MEMORY_DIR#"$AD"/}"
cur=$(python3 -c "import os;p=os.path.realpath('$scwd');w='$LANES/';print(p[len(w):].split('/')[0] if p.startswith(w) else '')")

# ---- human screen (systemMessage) -------------------------------------------------------------
if [ -n "${LANE_SCREEN:-}" ]; then
  if [ -n "$cur" ] && [ -f "$(lane_file "$cur")" ]; then
    "$PRODUCT/scripts/lane-brief" "$cur" 2>/dev/null
    echo; echo "commands: ! lane-menu   (prefix any lane-* command with \"! \" to run it here without a model call)"
  else
    lane_migrate_reminder
    echo "LANES"
    for f in "$LANES_DIR"/*.md; do [ -f "$f" ] || continue; id=$(basename "$f" .md); st=$(lane_get "$id" status)
      line="  $id  [$st]"
      while read -r r branch; do d="$LANES/$id/$r"
        if [ -d "$d" ]; then line="$line  $r ↑$(lane_unpushed "$d") ✎$(lane_dirty_count "$d")"; else line="$line  $r (no worktree)"; fi
      done < <(lane_repos "$id")
      echo "$line"
    done
    [ "$source" = "resume" ] && [ -n "$repo" ] && echo && echo "RESUMED conversation belongs to: $repo — Claude will offer where to continue."
    echo; "$PRODUCT/scripts/menu"
  fi
  exit 0
fi

if [ "$source" = "resume" ] && [ -n "$repo" ]; then
  echo "## RESUMED CONVERSATION — it belongs to repo '$repo' (transcript lives in that repo's project folder)."
  echo "Its earlier turns refer to OLD checkout paths. Those copies are frozen and blocked. Translate every mention:"
  echo "    old path in the transcript                                   -> what it means now"
  python3 - "$repo" "$LANES" "$REGISTRY" "${REPOS#"$AD"/}" <<'PY'
import json,sys,os,glob
repo,LANES,REGISTRY,REPOS_REL=sys.argv[1:]
AD=os.path.dirname(LANES)
try: olds=[k for k in json.load(open(f"{REGISTRY}/old-checkouts.json")) if k.rstrip("/").endswith("/"+repo)]
except (OSError, ValueError): olds=[]
wts=sorted(glob.glob(f"{LANES}/*/{repo}"))
target=(wts[0] if len(wts)==1 else ("lanes/<id>/"+repo+" (the lane you enter)")).replace(AD+"/","")
for o in olds: print(f"    {o:60} -> {target}")
print(f"    {REPOS_REL+'/'+repo+' (mirror)':60} -> not a place to work; never mention it")
PY
  echo "When you report state, use only the STATE block that arrives with each prompt. Never compare against old copies."
  wts=$(ls -d "$LANES"/*/"$repo" 2>/dev/null | sed "s|$LANES/||; s|/$repo||" || true)
  if [ -n "$cur" ]; then
    if [ -d "$LANES/$cur/$repo" ]; then echo "You are already inside lane '$cur', which has this repo. Re-anchor every path to $LANES/$cur/$repo and continue."
    else echo "WARNING: you are inside lane '$cur' but it has no worktree for '$repo'. Offer: ${X}lane-with $cur $repo, or switch lane."; fi
  else
    echo
    echo "YOUR FIRST MESSAGE, before answering anything else, must say which repo this is and offer these choices:"
    if [ -n "$wts" ]; then for w in $wts; do echo "  - continue in existing lane '$w' → EnterWorktree name=\"$w\"  (status: $(lane_get "$w" status); note: $(sed -n '/^## Resume note/,/^## /{/^## Resume note/d;/^## /d;p;}' "$(lane_file "$w")" | grep -v '^$' | head -1 | cut -c1-120))"; done; fi
    echo "  - start a NEW lane for it → ask for a short id (ticket key or slug), then EnterWorktree name=\"<id>\", then write its Goal from this conversation"
    echo "  - read-only: just answer questions, no worktree"
    echo "Recommend one and WAIT for their answer. Even if their message is a concrete request, do not enter or create a worktree until they have chosen."
  fi
  echo
fi

if [ "${1:-}" = "--worktree" ] || [ -n "$cur" ]; then
  id="$cur"
  if [ -n "$id" ] && [ -f "$(lane_file "$id")" ]; then
    echo "## lane — session in lane '$id' ($(basename "$scwd"))"; echo
    cat "$(lane_file "$id")"; echo
    echo "Read $MEM_REL/<repo>/MEMORY.md for each repo above, then brief $OWNER in five lines and continue the work."
    echo "Scope: only lanes/$id/. Park with ${X}lane-park $id \"<note>\" before they switch away."
    if [ "$LANE_MODE" = workspace ]; then
      echo "Lane commands (lane-brief, lane-park, lane-memory, …) are on PATH: call them by name, e.g. lane-brief $id."
    else
      echo "Lane scripts: call them by ABSOLUTE path, $PRODUCT/scripts/<name> (e.g. $PRODUCT/scripts/lane-brief $id). You are in the lane, so a relative scripts/<name> does not exist here and exits 127."
    fi
    # a workspace hands the lane's rules (LANE.md) to a session started inside the lane too, not only after EnterWorktree
    if [ "$LANE_MODE" = workspace ]; then echo; python3 -B "$PRODUCT/scripts/roots.py" lane-context "$id" </dev/null; fi
  fi
  exit 0
fi

echo "## lane dispatcher — board at $(date '+%F %H:%M')"
echo
# REPOLANE.md never carries a name (it is the product's text); the owner is named here, at run time
[ "$LANE_MODE" = workspace ] && { echo "Owner of this workspace: $OWNER (REPOLANE.md calls them \"the owner\")."; echo; }
for f in "$LANES_DIR"/*.md; do [ -f "$f" ] || continue; id=$(basename "$f" .md)
  st=$(lane_get "$id" status); up=$(lane_get "$id" updated)
  line="- **$id** [$st, updated $up]"
  while read -r r branch; do d="$LANES/$id/$r"
    if [ -d "$d" ]; then line="$line · $r/$branch ($(lane_dirty_count "$d") dirty, $(lane_unpushed_text "$d"))"
    else line="$line · $r/$branch (no worktree yet)"; fi
  done < <(lane_repos "$id")
  echo "$line"
  note=$(sed -n '/^## Resume note/,/^## /{/^## Resume note/d;/^## /d;p;}' "$f" | grep -v '^$' | head -1 | cut -c1-160)
  [ -n "$note" ] && echo "    $note"
done
echo
echo "Repos: $(ls "$REPOS" | tr '\n' ' ')"
echo
if [ "$LANE_MODE" = workspace ]; then
  echo "Commands: lane and the lane-* commands are on PATH; call them by name, here and after EnterWorktree (e.g. lane-brief <id>)."
  echo "Workspace data: $DATA (registry, memory, knowledge, mirrors). The rules: $DATA/REPOLANE.md, and LANE.md inside a lane."
else
  echo "Scripts dir (absolute): $PRODUCT/scripts"
  echo "After EnterWorktree the session sits in the lane, not here: call every lane script by absolute path, $PRODUCT/scripts/<name>"
  echo "(e.g. $PRODUCT/scripts/lane-brief <id>). A relative scripts/<name> exits 127 from the lane root. The scripts/<name> paths below are relative to the control plane: prefix them with the absolute dir above."
fi
# the instructions are written in a clone's words; a workspace gets them in its own (roots.py words)
lane_words <<'TXT'
Dispatcher instructions (details in CLAUDE.md "Dispatcher mode"):
- Discuss before deciding: propose ids, repos, branches, deletions, global-config changes and design choices in one
  line with a recommendation, then wait. Run directly only mechanical, reversible, explicitly requested steps.
- Be a visible operator: every time you run a lane-* script, enter or leave a worktree, or change a lane file,
  say so in one line. Never do these silently.
- Fresh session: list the active lanes above, one line each, and ask which one or what new work to start.
- Resume: scripts/lane-resume <id>, then EnterWorktree name="<lane-id>". New: scripts/lane-start <id> <repo>…, then
  EnterWorktree name="<lane-id>". A name is the only way in (no path, no repo); you land at the lane root and
  reach each repo at <repo>/… .
- Add repo to lane: scripts/lane-with. New repo under management: scripts/lane-add. Old chats: scripts/sessions <repo>,
  then hand over `claude --resume <session-id>` (any folder); they cannot be switched into mid-session.
- Leave: scripts/lane-park <id> "<note>" then ExitWorktree keep.
- If asked what they can do, show the menu below verbatim.
TXT
"$PRODUCT/scripts/menu"
