#!/bin/bash

echo "========================================"
echo "  🐳 Docker Build & Push Script"
echo "========================================"
echo ""

# Nombre del registry
REGISTRY="registry-pons.duckdns.org"
DEFAULT_IMAGE="bots-translation"

# Preguntar nombre de imagen
read -p "Nombre de la imagen [$DEFAULT_IMAGE]: " IMAGE_NAME
IMAGE_NAME=${IMAGE_NAME:-$DEFAULT_IMAGE}

# Preguntar tag
echo ""
echo "Tags disponibles:"
echo "  1) latest"
echo "  2) v1"
echo "  3) Personalizado"
read -p "Selecciona tag (1-3): " TAG_CHOICE

case $TAG_CHOICE in
    1) TAG="latest" ;;
    2) TAG="v1" ;;
    3) 
        read -p "Introduce el tag: " CUSTOM_TAG
        TAG=${CUSTOM_TAG:-$DEFAULT_IMAGE}
        ;;
    *) TAG="latest" ;;
esac

FULL_IMAGE="$REGISTRY/$IMAGE_NAME:$TAG"

# Preguntar si usar cache
echo ""
read -p "¿Usar cache de Docker? (s/n): " USE_CACHE
if [[ "$USE_CACHE" == "s" || "$USE_CACHE" == "S" || "$USE_CACHE" == "" ]]; then
    CACHE_FLAG=""
    CACHE_DESC="con cache"
else
    CACHE_FLAG="--no-cache"
    CACHE_DESC="sin cache"
fi

# Confirmar
echo ""
echo "========================================"
echo "  📋 Resumen de configuración:"
echo "========================================"
echo "  Imagen: $FULL_IMAGE"
echo "  Build:  $CACHE_DESC"
echo "========================================"
echo ""

read -p "¿Continuar? (s/n): " CONFIRM
if [[ "$CONFIRM" != "s" && "$CONFIRM" != "S" && "$CONFIRM" != "" ]]; then
    echo "❌ Cancelado"
    exit 0
fi

# Build
echo ""
echo "🔨 Construyendo imagen..."
echo "========================================"
docker build $CACHE_FLAG -t "$FULL_IMAGE" .

if [ $? -ne 0 ]; then
    echo "❌ Error en el build"
    exit 1
fi

echo ""
echo "✅ Build completado exitosamente"

# Push
echo ""
echo "📤 Subiendo a $REGISTRY..."
echo "========================================"
docker push "$FULL_IMAGE"

if [ $? -ne 0 ]; then
    echo "❌ Error al subir la imagen"
    exit 1
fi

echo ""
echo "========================================"
echo "  🎉 ¡Completado!"
echo "========================================"
echo ""
echo "  Imagen: $FULL_IMAGE"
echo ""
echo "  Para ejecutar:"
echo "  docker run -d -p 8000:8000 \\"
echo "    -e DISCORD_TOKEN=... \\"
echo "    -e TELEGRAM_TOKEN=... \\"
echo "    -e ADMIN_PASSWORD=... \\"
echo "    $FULL_IMAGE"
echo ""
