#!/bin/bash
# verify-worktree.sh — Verifica build, tests y cierre de issue en un worktree
#
# Uso: ./verify-worktree.sh <worktree-path>
# Ejemplo: ./verify-worktree.sh worktrees/0026-split-runtime
#
# Checks:
#   1. El worktree existe y tiene commits propios
#   2. go build -tags goolm ./... compila
#   3. go test -tags goolm ./... pasa
#   4. El issue fue movido a completed/
#
# Exit codes:
#   0 = todo OK
#   1 = error de argumento
#   2 = build falló
#   3 = tests fallaron
#   4 = issue no cerrado
#   5 = sin commits propios

set -euo pipefail

if [ $# -lt 1 ]; then
  echo "ERROR: se necesita el path del worktree"
  echo "Uso: $0 <worktree-path>"
  exit 1
fi

WORKTREE="$1"

# Resolver path absoluto
if [[ "$WORKTREE" != /* ]]; then
  REPO_ROOT="$(git rev-parse --show-toplevel)"
  WORKTREE="${REPO_ROOT}/${WORKTREE}"
fi

if [ ! -d "$WORKTREE" ]; then
  echo "ERROR: worktree no encontrado: ${WORKTREE}"
  exit 1
fi

SLUG="$(basename "$WORKTREE")"
echo "=== Verificando: ${SLUG} ==="

# 1. Verificar commits propios
echo "--- Commits propios ---"
COMMIT_COUNT=$(cd "$WORKTREE" && git log master..HEAD --oneline 2>/dev/null | wc -l)
if [ "$COMMIT_COUNT" -eq 0 ]; then
  echo "FAIL: sin commits propios en la branch"
  exit 5
fi
echo "OK: ${COMMIT_COUNT} commits desde master"
cd "$WORKTREE" && git log master..HEAD --oneline

# 2. Build
echo ""
echo "--- Build ---"
if (cd "$WORKTREE" && go build -tags goolm ./... 2>&1); then
  echo "OK: build exitoso"
else
  echo "FAIL: build falló"
  exit 2
fi

# 3. Tests
echo ""
echo "--- Tests ---"
if (cd "$WORKTREE" && go test -tags goolm ./... 2>&1); then
  echo "OK: tests pasaron"
else
  echo "FAIL: tests fallaron"
  exit 3
fi

# 4. Issue cerrado (movido a completed/)
echo ""
echo "--- Cierre de issue ---"
COMPLETED_FILES=$(cd "$WORKTREE" && git diff --name-only master -- dev/issues/completed/ 2>/dev/null | wc -l)
if [ "$COMPLETED_FILES" -gt 0 ]; then
  echo "OK: issue movido a completed/"
  cd "$WORKTREE" && git diff --name-only master -- dev/issues/completed/
else
  echo "WARN: no se detectó issue movido a completed/ (verificar manualmente)"
  # No es un error fatal — puede que el issue no siga la convención exacta
fi

echo ""
echo "=== RESULTADO: ${SLUG} — OK ==="
