#!/usr/bin/env bash
# sessions <repo|lane-id> [n]  — list resumable conversations for a repo (newest first)
source "$(python3 -c 'import os,sys;print(os.path.dirname(os.path.realpath(sys.argv[1])))' "$0")/lib.sh"
source "$PRODUCT/scripts/gitstate.sh"
key="${1:-}"; n="${2:-10}"; [ -n "$key" ] || die "usage: sessions <repo|lane-id> [n]"

# A lane id resolves to exactly one worktree — no union needed, current behaviour unchanged.
if ! [ -d "$REPOS/$key" ]; then
  repo=$(lane_repos "$key" 2>/dev/null | head -1 | cut -d' ' -f1)
  [ -n "$repo" ] && [ -d "$REPOS/$repo" ] || die "unknown repo/lane '$key'"
  projs=("$LANES/$key/$repo")
  old_n=0; old_path=""
else
  repo="$key"
  # Three sources of sessions for a repo, none of which is the mirror (repos/<repo> is never a
  # session cwd — the guard refuses cd-ing into it):
  #   1. every live lane worktree that has this repo
  #   2. every finished lane's worktree path, reconstructed even though the folder is gone
  #   3. the repo's pre-Repolane old checkout, if any (registry/repos.yaml old_paths:) — reported
  #      separately, since those sessions are not directly resumable from a lane worktree
  declare -a projs=()
  for lf in "$LANES_DIR"/*.md "$LANES_DIR"/done/*.md; do
    [ -f "$lf" ] || continue
    id=$(basename "$lf" .md)
    while read -r r b; do
      [ "$r" = "$repo" ] || continue
      projs+=("$LANES/$id/$repo")
    done < <(sed -n '/^---$/,/^---$/p' "$lf" | awk '/^  - repo:/{r=$3} /^    branch:/{print r, $2}')
  done
  # source #3: the pre-Repolane checkout this repo was added from, if any
  old_path=$(sed -n "/^  $repo:\$/,/^  [a-z]/p" "$REGISTRY/repos.yaml" | sed -n 's/^      - //p' | head -1)
  old_n=0
  if [ -n "$old_path" ]; then old_n=$(lane_agent session-count "$old_path"); fi
fi
lane_agent sessions "$n" "$repo" "${projs[@]}"
if [ "${old_n:-0}" -gt 0 ] 2>/dev/null; then
  echo "  $old_n more conversation(s) at the original checkout ($old_path), not yet imported — bring them in with: lane import"
fi
