#!/bin/bash

# ========================================
# Script: clone-to-new-repo.sh
# Descripción: Clona CD-System desde el repositorio central hacia un nuevo repositorio
# Uso: ./clone-to-new-repo.sh <url_repositorio_destino>
# Ejemplo: ./clone-to-new-repo.sh https://github.com/LACOMPANIADIGITAL/nuevo-proyecto.git
# ========================================

# Colores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Función para mostrar mensajes con colores
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

# Verificar que se proporcione el repositorio destino
if [ $# -eq 0 ]; then
    print_error "Debes proporcionar la URL del repositorio destino"
    echo "Uso: $0 <url_repositorio_destino>"
    echo "Ejemplo: $0 https://github.com/LACOMPANIADIGITAL/nuevo-proyecto.git"
    exit 1
fi

DEST_REPO=$1
CD_SYSTEM_REPO="https://github.com/LACOMPANIADIGITAL/cd-system.git"
CD_SYSTEM_BRANCH="cd-system"
TEMP_REMOTE="cd-system-source"

# Detectar si existe cd-system local
CD_SYSTEM_LOCAL_DIR=""
CURRENT_DIR="$(pwd)"
PARENT_DIR="$(cd .. && pwd)"

# Buscar cd-system en el directorio padre
if [ -d "$PARENT_DIR/cd-system" ] && [ -f "$PARENT_DIR/cd-system/.git/config" ]; then
    CD_SYSTEM_LOCAL_DIR="$PARENT_DIR/cd-system"
    # Verificar que tenga la rama cd-system
    if git -C "$CD_SYSTEM_LOCAL_DIR" show-ref --verify --quiet "refs/heads/$CD_SYSTEM_BRANCH" 2>/dev/null; then
        print_message "✅ Directorio local de cd-system detectado: ${CYAN}$CD_SYSTEM_LOCAL_DIR${NC}"
        print_message "   Usando fuente local (más rápido que descargar desde GitHub)"
    else
        CD_SYSTEM_LOCAL_DIR=""
        print_warning "cd-system local encontrado pero no tiene la rama $CD_SYSTEM_BRANCH"
        print_message "   Usando GitHub como fuente"
    fi
fi

# Determinar la fuente a usar
if [ -n "$CD_SYSTEM_LOCAL_DIR" ]; then
    CD_SYSTEM_SOURCE="$CD_SYSTEM_LOCAL_DIR"
    SOURCE_TYPE="local"
else
    CD_SYSTEM_SOURCE="$CD_SYSTEM_REPO"
    SOURCE_TYPE="remote"
fi

print_message "═══════════════════════════════════════════════════════════"
print_message "Clonación de CD-System hacia nuevo repositorio"
print_message "═══════════════════════════════════════════════════════════"
echo
print_message "Repositorio destino: ${CYAN}$DEST_REPO${NC}"
if [ "$SOURCE_TYPE" == "local" ]; then
    print_message "Repositorio origen:  ${CYAN}$CD_SYSTEM_SOURCE${NC} (local)"
else
    print_message "Repositorio origen:  ${CYAN}$CD_SYSTEM_SOURCE${NC} (GitHub)"
fi
print_message "Rama:               ${CYAN}$CD_SYSTEM_BRANCH${NC}"
echo

# Verificar que estamos en un repositorio git
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    print_error "No estás en un repositorio git válido"
    print_message "Inicializando repositorio git..."
    git init
fi

# Verificar que el repositorio destino esté configurado como origin
if git remote | grep -q "^origin$"; then
    CURRENT_ORIGIN=$(git remote get-url origin)
    if [ "$CURRENT_ORIGIN" != "$DEST_REPO" ]; then
        print_warning "El remote 'origin' apunta a: $CURRENT_ORIGIN"
        read -p "¿Deseas actualizarlo a $DEST_REPO? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            git remote set-url origin "$DEST_REPO"
            print_success "Remote 'origin' actualizado"
        fi
    fi
else
    print_step "1. Configurando remote 'origin'..."
    git remote add origin "$DEST_REPO"
    print_success "Remote 'origin' configurado"
fi

# Verificar/agregar remote temporal de cd-system
if git remote | grep -q "^$TEMP_REMOTE$"; then
    print_warning "El remote '$TEMP_REMOTE' ya existe. Actualizando..."
    git remote set-url "$TEMP_REMOTE" "$CD_SYSTEM_SOURCE"
else
    print_step "2. Agregando remote temporal de CD-System..."
    if [ "$SOURCE_TYPE" == "local" ]; then
        print_message "   Usando directorio local (sin descarga desde internet)"
    else
        print_message "   Usando GitHub (requiere conexión a internet)"
    fi
    git remote add "$TEMP_REMOTE" "$CD_SYSTEM_SOURCE"
    print_success "Remote temporal agregado"
fi

# Fetch de la rama cd-system
if [ "$SOURCE_TYPE" == "local" ]; then
    print_step "3. Obteniendo rama $CD_SYSTEM_BRANCH desde CD-System local..."
    print_message "   (Instantáneo, sin descarga desde internet)"
else
    print_step "3. Descargando rama $CD_SYSTEM_BRANCH desde CD-System..."
    print_message "   (Esto puede tardar dependiendo de tu conexión)"
fi

git fetch "$TEMP_REMOTE" "$CD_SYSTEM_BRANCH"

if [ $? -ne 0 ]; then
    print_error "Error al hacer fetch de la rama $CD_SYSTEM_BRANCH"
    
    # Si falló con local, intentar con GitHub como fallback
    if [ "$SOURCE_TYPE" == "local" ]; then
        print_warning "Error con fuente local, intentando con GitHub como fallback..."
        git remote set-url "$TEMP_REMOTE" "$CD_SYSTEM_REPO"
        git fetch "$TEMP_REMOTE" "$CD_SYSTEM_BRANCH"
        
        if [ $? -ne 0 ]; then
            print_error "Error al hacer fetch desde GitHub también"
            git remote remove "$TEMP_REMOTE" 2>/dev/null || true
            exit 1
        fi
        print_success "Rama $CD_SYSTEM_BRANCH descargada desde GitHub (fallback)"
    else
        git remote remove "$TEMP_REMOTE" 2>/dev/null || true
        exit 1
    fi
else
    if [ "$SOURCE_TYPE" == "local" ]; then
        print_success "Rama $CD_SYSTEM_BRANCH obtenida desde local (instantáneo)"
    else
        print_success "Rama $CD_SYSTEM_BRANCH descargada desde GitHub"
    fi
fi

# Verificar si la rama cd-system ya existe localmente
if git show-ref --verify --quiet "refs/heads/$CD_SYSTEM_BRANCH"; then
    print_warning "La rama '$CD_SYSTEM_BRANCH' ya existe localmente"
    read -p "¿Deseas sobrescribirla? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_step "4. Cambiando a otra rama antes de eliminar..."
        # Cambiar a otra rama si estamos en cd-system
        CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
        if [ "$CURRENT_BRANCH" == "$CD_SYSTEM_BRANCH" ]; then
            # Intentar cambiar a main o crear una rama temporal
            if git show-ref --verify --quiet "refs/heads/main"; then
                git checkout main 2>/dev/null || git checkout -b temp-branch 2>/dev/null || true
            else
                git checkout -b temp-branch 2>/dev/null || true
            fi
        fi
        print_step "   Eliminando rama existente..."
        git branch -D "$CD_SYSTEM_BRANCH" 2>/dev/null || true
    else
        print_message "Operación cancelada por el usuario"
        git remote remove "$TEMP_REMOTE" 2>/dev/null || true
        exit 0
    fi
fi

# Crear rama cd-system desde el remote
print_step "4. Creando rama local '$CD_SYSTEM_BRANCH'..."
# Usar checkout -B para forzar la creación/actualización
git checkout -B "$CD_SYSTEM_BRANCH" "$TEMP_REMOTE/$CD_SYSTEM_BRANCH"

if [ $? -ne 0 ]; then
    print_error "Error al crear la rama $CD_SYSTEM_BRANCH"
    git remote remove "$TEMP_REMOTE" 2>/dev/null || true
    exit 1
fi

print_success "Rama $CD_SYSTEM_BRANCH creada"

# Verificar que .gitattributes existe y tiene las protecciones
print_step "5. Verificando protección de archivos del sistema..."
GITATTRIBUTES_FIXED=false
if [ -f ".gitattributes" ]; then
    if grep -q "merge=ours" .gitattributes; then
        print_success ".gitattributes configurado con protecciones"
    else
        print_warning ".gitattributes existe pero no tiene configuraciones de merge=ours"
        print_message "Corrigiendo automáticamente desde el repositorio central..."

        # Intentar copiar desde el remote temporal si aún existe
        if git remote | grep -q "^$TEMP_REMOTE$"; then
            # Hacer checkout temporal del .gitattributes desde el core
            git show "$TEMP_REMOTE/$CD_SYSTEM_BRANCH:.gitattributes" > .gitattributes 2>/dev/null
            if [ $? -eq 0 ] && grep -q "merge=ours" .gitattributes; then
                git add .gitattributes
                git commit -m "chore: Corregir .gitattributes con protecciones del sistema" >/dev/null 2>&1
                print_success ".gitattributes corregido automáticamente"
                GITATTRIBUTES_FIXED=true
            fi
        fi

        if [ "$GITATTRIBUTES_FIXED" == "false" ]; then
            print_warning "No se pudo corregir automáticamente"
            print_message "Por favor, copia manualmente .gitattributes desde el repositorio central:"
            echo "  cp ../cd-system/.gitattributes ."
            echo "  git add .gitattributes"
            echo "  git commit -m 'chore: Agregar protección de archivos del sistema'"
        fi
    fi
else
    print_warning ".gitattributes no encontrado"
    print_message "Agregando .gitattributes desde el repositorio central..."

    # Intentar copiar desde el remote temporal si aún existe
    if git remote | grep -q "^$TEMP_REMOTE$"; then
        git show "$TEMP_REMOTE/$CD_SYSTEM_BRANCH:.gitattributes" > .gitattributes 2>/dev/null
        if [ $? -eq 0 ] && [ -f ".gitattributes" ]; then
            git add .gitattributes
            git commit -m "chore: Agregar .gitattributes para protección de archivos del sistema" >/dev/null 2>&1
            print_success ".gitattributes agregado automáticamente"
            GITATTRIBUTES_FIXED=true
        fi
    fi

    if [ "$GITATTRIBUTES_FIXED" == "false" ]; then
        print_error "No se pudo agregar automáticamente"
        print_message "Por favor, copia manualmente .gitattributes desde el repositorio central:"
        echo "  cp ../cd-system/.gitattributes ."
        echo "  git add .gitattributes"
        echo "  git commit -m 'chore: Agregar protección de archivos del sistema'"
    fi
fi

# Verificar archivos protegidos críticos
print_step "6. Verificando archivos críticos del sistema..."
CRITICAL_FILES=(
    "config/cd-system.php"
    "config/site.php"
    "public/cd-project/assets/logo.png"
)

MISSING_FILES=()
for file in "${CRITICAL_FILES[@]}"; do
    if [ ! -f "$file" ]; then
        MISSING_FILES+=("$file")
    fi
done

if [ ${#MISSING_FILES[@]} -eq 0 ]; then
    print_success "Todos los archivos críticos están presentes"
else
    print_warning "Archivos críticos faltantes:"
    for file in "${MISSING_FILES[@]}"; do
        echo "  - $file"
    done
fi

# Remover remote temporal
print_step "7. Limpiando remotes temporales..."
git remote remove "$TEMP_REMOTE" 2>/dev/null || true
print_success "Remote temporal removido"

# Mostrar estado final
echo
print_message "═══════════════════════════════════════════════════════════"
print_success "¡Clonación completada exitosamente!"
print_message "═══════════════════════════════════════════════════════════"
echo
print_message "Estado actual:"
git branch -v
echo
print_message "Remotes configurados:"
git remote -v
echo
print_message "═══════════════════════════════════════════════════════════"
print_message "Próximos pasos:"
echo
echo "  1. Revisar la configuración del proyecto:"
echo "     - config/cd-system.php"
echo "     - config/site.php"
echo
echo "  2. Personalizar la identidad del proyecto:"
echo "     - public/cd-project/assets/ (logos, favicons)"
echo "     - config/demos/[demo-name]/ (configuraciones específicas)"
echo
echo "  3. Subir la rama al repositorio:"
echo "     ${CYAN}git push -u origin $CD_SYSTEM_BRANCH${NC}"
echo
echo "  4. Configurar el proyecto:"
echo "     ${CYAN}composer install${NC}"
echo "     ${CYAN}cp .env.example .env${NC}"
echo "     ${CYAN}php artisan key:generate${NC}"
echo
print_message "═══════════════════════════════════════════════════════════"

