#!/usr/bin/env bash
# lane-resume <id>: recreate missing worktrees, refresh guards, print the state.
source "$(python3 -c 'import os,sys;print(os.path.dirname(os.path.realpath(sys.argv[1])))' "$0")/lib.sh"
source "$PRODUCT/scripts/gitstate.sh"
# A worktree folder deleted by hand leaves git still believing it exists, and every attempt
# to recreate it fails. Clearing those stale registrations first is what makes resume a repair.
prune_all(){ for r in "$REPOS"/*/; do [ -d "$r/.git" ] || [ -f "$r/.git" ] || continue
               git -C "$r" worktree prune 2>/dev/null || true; done; }
prune_all
id="${1:-}"; [ -f "$(lane_file "$id")" ] || die "no lane '$id'"
while read -r repo branch; do
  dst="$LANES/$id/$repo"
  if [ ! -e "$dst" ]; then
    if git -C "$REPOS/$repo" show-ref --verify -q "refs/heads/$branch"; then git -C "$REPOS/$repo" worktree add -q "$dst" "$branch" && echo "recreated $dst on $branch"
    else git -C "$REPOS/$repo" worktree add -q -b "$branch" "$dst" "origin/$(repo_default "$repo")" && echo "created $dst on new branch $branch"; fi
  fi
  [ -d "$dst" ] && link_env "$repo" "$dst"
done < <(lane_repos "$id")
lane_anchor "$id"
lane_set_status "$id" active; write_lane_claude "$id"; refresh_guards
echo "=== $(lane_file "$id")"; cat "$(lane_file "$id")"
echo; while read -r repo branch; do d="$LANES/$id/$repo"; echo "--- $repo [$branch] $(lane_dirty_count "$d") dirty, $(lane_unpushed_text "$d")"; git -C "$d" log --oneline -3; done < <(lane_repos "$id")
"$PRODUCT/scripts/lane-workspace" >/dev/null
echo; echo "next: cd $LANES/$id && claude"
