#!/bin/bash
# verify-worktree.sh — Verifica build, tests y cierre de issue en un worktree
#
# Uso: ./verify-worktree.sh <worktree-path> [build-tag]
# Ejemplos:
#   ./verify-worktree.sh worktrees/0026-split-runtime fts5
#   BUILD_TAG=goolm ./verify-worktree.sh worktrees/0026-split-runtime
#   ./verify-worktree.sh worktrees/0026-split-runtime           # sin -tags
#
# El build tag se puede pasar como:
#   - segundo argumento posicional
#   - variable de entorno BUILD_TAG
#   - auto-detección via //go:build en los .go del worktree
#   - si sigue vacío, ejecuta sin -tags
#
# Checks:
#   1. El worktree existe y tiene commits propios
#   2. go build ${BUILD_TAG:+-tags $BUILD_TAG} ./... compila
#   3. go test  ${BUILD_TAG:+-tags $BUILD_TAG} ./... 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> [build-tag]"
  exit 1
fi

WORKTREE="$1"
BUILD_TAG="${2:-${BUILD_TAG:-}}"

# 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} ==="

# Auto-detectar build tag si no se pasó
if [ -z "$BUILD_TAG" ]; then
  AUTO_TAG=$(grep -rh "^//go:build " --include="*.go" "$WORKTREE" 2>/dev/null \
    | sed -E 's|^//go:build ([a-zA-Z0-9_]+).*|\1|' \
    | sort -u \
    | head -1 || true)
  if [ -n "$AUTO_TAG" ]; then
    BUILD_TAG="$AUTO_TAG"
    echo "INFO: build tag auto-detectado: ${BUILD_TAG}"
  else
    echo "INFO: sin build tag (go build/test sin -tags)"
  fi
fi

TAG_FLAG=""
if [ -n "$BUILD_TAG" ]; then
  TAG_FLAG="-tags $BUILD_TAG"
fi

# 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 (go build $TAG_FLAG ./...) ---"
if (cd "$WORKTREE" && go build $TAG_FLAG ./... 2>&1); then
  echo "OK: build exitoso"
else
  echo "FAIL: build falló"
  exit 2
fi

# 3. Tests
echo ""
echo "--- Tests (go test $TAG_FLAG ./...) ---"
if (cd "$WORKTREE" && go test $TAG_FLAG ./... 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)"
fi

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