#!/usr/bin/env bash
set -euo pipefail

# === Config predeterminada (podés override con flags) ===
PROJECT_REPO_URL="https://github.com/LACOMPANIADIGITAL/copitohelados.git"
PROJECT_BRANCH="cd-system"
TARGET_BRANCH="cd-system"
TEMP_REMOTE="project-src"
MODE="merge"   # merge | replace
PUSH="yes"     # yes | no
SHALLOW="no"   # yes | no  (si "yes", hace fetch --depth=1)

usage() {
  cat <<EOF
Uso: $(basename "$0") [opciones]

Opciones:
  --project-url URL       URL del repo del proyecto (default: $PROJECT_REPO_URL)
  --project-branch NAME   Rama en el proyecto (default: $PROJECT_BRANCH)
  --target-branch NAME    Rama en ESTE repo (default: $TARGET_BRANCH)
  --mode MODE             merge | replace  (default: $MODE)
  --push yes|no           push a origin luego de integrar (default: $PUSH)
  --shallow yes|no        usar fetch --depth=1 (default: $SHALLOW)
  -h, --help              mostrar ayuda

Ejemplos:
  $(basename "$0") --mode merge
  $(basename "$0") --mode replace --push yes
  $(basename "$0") --project-url https://github.com/LACOMPANIADIGITAL/otro.git
EOF
}

# === Parseo simple de flags ===
while [[ $# -gt 0 ]]; do
  case "$1" in
    --project-url)    PROJECT_REPO_URL="$2"; shift 2 ;;
    --project-branch) PROJECT_BRANCH="$2"; shift 2 ;;
    --target-branch)  TARGET_BRANCH="$2"; shift 2 ;;
    --mode)           MODE="$2"; shift 2 ;;
    --push)           PUSH="$2"; shift 2 ;;
    --shallow)        SHALLOW="$2"; shift 2 ;;
    -h|--help)        usage; exit 0 ;;
    *) echo "Opción desconocida: $1"; usage; exit 1 ;;
  esac
done

echo ">> Verificando repositorio Git actual..."
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "No es un repo Git"; exit 1; }

echo ">> Cambiando a rama destino: $TARGET_BRANCH"
if git show-ref --verify --quiet "refs/heads/$TARGET_BRANCH"; then
  git switch "$TARGET_BRANCH"
else
  echo "La rama local '$TARGET_BRANCH' no existe. Creándola vacía..."
  git switch --orphan "$TARGET_BRANCH"
  git reset --hard
fi

echo ">> Agregando/actualizando remoto temporal: $TEMP_REMOTE"
if git remote get-url "$TEMP_REMOTE" >/dev/null 2>&1; then
  git remote set-url "$TEMP_REMOTE" "$PROJECT_REPO_URL"
else
  git remote add "$TEMP_REMOTE" "$PROJECT_REPO_URL"
fi

echo ">> Fetch de $PROJECT_BRANCH desde $PROJECT_REPO_URL"
if [[ "$SHALLOW" == "yes" ]]; then
  git fetch --depth=1 "$TEMP_REMOTE" +refs/heads/$PROJECT_BRANCH:refs/remotes/$TEMP_REMOTE/$PROJECT_BRANCH
else
  git fetch "$TEMP_REMOTE" +refs/heads/$PROJECT_BRANCH:refs/remotes/$TEMP_REMOTE/$PROJECT_BRANCH
fi

echo ">> Integrando cambios con modo: $MODE"
case "$MODE" in
  merge)
    # Merge preservando historias (para repos sin historia común)
    if ! git merge --no-edit --allow-unrelated-histories "refs/remotes/$TEMP_REMOTE/$PROJECT_BRANCH"; then
      echo ">> Conflictos detectados. Resolvelos, luego ejecutá:"
      echo "   git add -A && git commit"
      exit 2
    fi
    ;;
  replace)
    # Reemplaza TODO el contenido e historial
    git reset --hard "refs/remotes/$TEMP_REMOTE/$PROJECT_BRANCH"
    ;;
  *)
    echo "Modo inválido: $MODE (usar 'merge' o 'replace')"
    exit 1
    ;;
esac

echo ">> Removiendo remoto temporal: $TEMP_REMOTE"
git remote remove "$TEMP_REMOTE" || true

if [[ "$PUSH" == "yes" ]]; then
  echo ">> Pusheando a origin/$TARGET_BRANCH"
  if [[ "$MODE" == "replace" ]]; then
    git push origin "$TARGET_BRANCH" --force
  else
    git push origin "$TARGET_BRANCH"
  fi
else
  echo ">> Push desactivado (--push no). Saltando."
fi

echo "✅ Listo. Rama '$TARGET_BRANCH' actualizada desde '$PROJECT_BRANCH' del proyecto."
