#!/usr/bin/env zsh
# worktree_manager.sh — create/list/cleanup git worktrees for agent isolation
#
# Worktrees are created at <REPO>/.git/worktrees/<name> so that:
#   cd .git/worktrees/<name> && zsh .orxaq/orxaq-orchestrate.sh
# works correctly from the repo root.
#
# Usage:
#   create <name>       — create worktree at .git/worktrees/<name>
#   list                — list all active worktrees
#   cleanup <name>      — remove named worktree and prune
#   cleanup-all         — remove all session-* worktrees

set -euo pipefail

REPO="$(cd "$(dirname "$0")/../.." && git rev-parse --show-toplevel 2>/dev/null || echo "$HOME/dev/orxaq")"
cd "$REPO"

cmd="${1:-list}"
name="${2:-}"

case "$cmd" in
  create)
    [[ -z "$name" ]] && { echo "Usage: $0 create <name>" >&2; exit 1; }
    wt_path="${REPO}/.git/worktrees/${name}"
    branch="worktree/${name}"

    if [[ -d "$wt_path" && -f "$wt_path/.git" ]]; then
      echo "[worktree] Already exists: $wt_path"
    else
      # Remove stale metadata if any
      [[ -d "${REPO}/.git/worktrees/${name}" ]] && git worktree prune 2>/dev/null || true

      git worktree add -b "$branch" "$wt_path" main 2>/dev/null || \
        git worktree add -B "$branch" "$wt_path" main 2>/dev/null || \
        git worktree add "$wt_path" main
      echo "[worktree] Created: $wt_path (branch: $branch)"
    fi

    # Symlink venv for faster startup
    if [[ ! -e "$wt_path/.venv" && -d "$REPO/.venv" ]]; then
      ln -sf "$REPO/.venv" "$wt_path/.venv"
    fi

    # Copy .env if present
    [[ -f "$REPO/.env" && ! -f "$wt_path/.env" ]] && cp "$REPO/.env" "$wt_path/.env"

    echo "$wt_path"
    ;;

  list)
    git worktree list
    ;;

  cleanup)
    [[ -z "$name" ]] && { echo "Usage: $0 cleanup <name>" >&2; exit 1; }
    wt_path="${REPO}/.git/worktrees/${name}"
    if [[ -d "$wt_path" ]]; then
      git worktree remove --force "$wt_path" 2>/dev/null || rm -rf "$wt_path"
      echo "[worktree] Removed: $wt_path"
    else
      echo "[worktree] Not found: $wt_path"
    fi
    git worktree prune
    ;;

  cleanup-all)
    for wt_meta in "${REPO}/.git/worktrees"/session-*/; do
      name_only="$(basename "$wt_meta")"
      wt_path="${REPO}/.git/worktrees/${name_only}"
      [[ -d "$wt_path" ]] || continue
      git worktree remove --force "$wt_path" 2>/dev/null || rm -rf "$wt_path"
      echo "[worktree] Removed: $wt_path"
    done
    git worktree prune
    echo "[worktree] Pruned."
    ;;

  *)
    echo "Usage: $0 {create|list|cleanup|cleanup-all} [name]" >&2
    exit 1
    ;;
esac
