#!/usr/bin/env bash
# Spin up (or tear down) an isolated worktree for one refactor task.
#
#   .agents/scripts/worktree.sh start 07 route-cards
#   .agents/scripts/worktree.sh finish 07 route-cards
#
# One task, one worktree, one agent. See .agents/rules/git-worktrees.md
set -euo pipefail

action=${1:?usage: worktree.sh <start|finish> <task-number> <slug>}
number=${2:?task number, e.g. 07}
slug=${3:?slug, e.g. route-cards}

dir="../af-task-${number}"
branch="refactor/task-${number}-${slug}"
plan="plans/astro-refactor/task-${number}-${slug}.md"

case "$action" in
  start)
    [ -f "$plan" ] || echo "warning: no plan at $plan — check the task number" >&2
    git fetch origin
    git worktree add "$dir" -b "$branch" origin/main

    # Not optional. `.husky/_` is generated by install and is NOT committed, so
    # a fresh worktree has hooks configured but absent — every commit would pass
    # unchecked. --prefer-offline keeps ten parallel spin-ups off the registry.
    ( cd "$dir" && pnpm install --frozen-lockfile && .agents/scripts/verify-hooks.sh )

    echo
    echo "worktree : $dir"
    echo "branch   : $branch"
    echo "brief    : $plan"
    echo
    echo "next: cd $dir && read the brief end to end before writing anything"
    ;;
  finish)
    # Never remove a worktree with uncommitted work in it.
    if [ -n "$(git -C "$dir" status --porcelain)" ]; then
      echo "refusing: $dir has uncommitted changes" >&2
      git -C "$dir" status --short >&2
      exit 1
    fi
    git worktree remove "$dir"
    echo "removed $dir — branch $branch kept; delete it after the merge lands"
    ;;
  *)
    echo "unknown action: $action (expected start|finish)" >&2
    exit 2
    ;;
esac
