#!/bin/bash
# setup-worktrees.sh — Crea git worktrees para ejecución paralela de issues
#
# Uso: ./setup-worktrees.sh <slug-1> <slug-2> ...
# Ejemplo: ./setup-worktrees.sh 0026-split-runtime 0027-prune-config-schema
#
# Cada slug genera:
#   worktrees/<slug>/  (worktree completo)
#   branch: issue/<slug>

set -euo pipefail

REPO_ROOT="$(git rev-parse --show-toplevel)"
WORKTREE_DIR="${REPO_ROOT}/worktrees"

if [ $# -eq 0 ]; then
  echo "ERROR: se necesita al menos un slug de issue"
  echo "Uso: $0 <slug-1> <slug-2> ..."
  exit 1
fi

# Asegurar que master está actualizado
echo "=== Actualizando master ==="
CURRENT_BRANCH="$(git branch --show-current)"
git checkout master 2>/dev/null
git pull --rebase 2>/dev/null || echo "WARN: no se pudo pull (sin remote o sin conexión)"

# Volver a la rama original si no era master
if [ "$CURRENT_BRANCH" != "master" ] && [ -n "$CURRENT_BRANCH" ]; then
  git checkout "$CURRENT_BRANCH" 2>/dev/null
fi

mkdir -p "$WORKTREE_DIR"

CREATED=0
SKIPPED=0
FAILED=0

for slug in "$@"; do
  branch="issue/${slug}"
  path="${WORKTREE_DIR}/${slug}"

  if [ -d "$path" ]; then
    echo "SKIP: worktree ya existe: ${path}"
    SKIPPED=$((SKIPPED + 1))
    continue
  fi

  # Verificar que la branch no existe ya
  if git show-ref --verify --quiet "refs/heads/${branch}" 2>/dev/null; then
    echo "WARN: branch ${branch} ya existe, creando worktree desde ella"
    git worktree add "$path" "$branch" 2>/dev/null || {
      echo "FAIL: no se pudo crear worktree para ${slug}"
      FAILED=$((FAILED + 1))
      continue
    }
  else
    echo "CREATE: worktree ${path} (branch ${branch})"
    git worktree add -b "$branch" "$path" master 2>/dev/null || {
      echo "FAIL: no se pudo crear worktree para ${slug}"
      FAILED=$((FAILED + 1))
      continue
    }
  fi

  CREATED=$((CREATED + 1))
done

echo ""
echo "=== Resumen ==="
echo "Creados: ${CREATED}"
echo "Existentes: ${SKIPPED}"
echo "Fallidos: ${FAILED}"
echo ""
echo "=== Worktrees activos ==="
git worktree list
