#!/bin/bash

# ========================================
# Script: verify-setup.sh
# Descripción: Verifica que todo esté listo para crear nuevos proyectos
# Uso: ./verify-setup.sh
# ========================================

# Colores
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

# Contador de verificaciones
PASSED=0
FAILED=0

print_header() {
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
}

print_check() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✅ $2${NC}"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}❌ $2${NC}"
        FAILED=$((FAILED + 1))
    fi
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# Obtener directorio del script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CD_SYSTEM_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$CD_SYSTEM_DIR"

print_header "Verificación del Sistema CD-System"
echo ""

# 1. Verificar scripts necesarios
echo -e "${CYAN}1. Scripts Necesarios:${NC}"
test -f scripts/create-new-project.sh
print_check $? "create-new-project.sh existe"

test -f scripts/clone-to-new-repo.sh
print_check $? "clone-to-new-repo.sh existe"

test -f scripts/setup_cd_project.sh
print_check $? "setup_cd_project.sh existe"

echo ""

# 2. Verificar permisos de ejecución
echo -e "${CYAN}2. Permisos de Ejecución:${NC}"
test -x scripts/create-new-project.sh
print_check $? "create-new-project.sh tiene permisos de ejecución"

test -x scripts/clone-to-new-repo.sh
print_check $? "clone-to-new-repo.sh tiene permisos de ejecución"

test -x scripts/setup_cd_project.sh
print_check $? "setup_cd_project.sh tiene permisos de ejecución"

echo ""

# 3. Verificar .gitattributes
echo -e "${CYAN}3. Protección de Archivos:${NC}"
if [ -f ".gitattributes" ]; then
    PROTECTION_COUNT=$(grep -c "merge=ours" .gitattributes 2>/dev/null || echo "0")
    if [ "$PROTECTION_COUNT" -gt 0 ]; then
        print_check 0 ".gitattributes tiene $PROTECTION_COUNT protecciones configuradas"
    else
        print_check 1 ".gitattributes NO tiene protecciones (merge=ours)"
    fi
else
    print_check 1 ".gitattributes no existe"
fi

# Verificar archivos protegidos específicos
PROTECTED_FILES=(
    "config/cd-system.php"
    "config/site.php"
    "public/cd-project/assets/logo.png"
)

for file in "${PROTECTED_FILES[@]}"; do
    if grep -q "$file merge=ours" .gitattributes 2>/dev/null; then
        print_check 0 "$file está protegido"
    else
        print_check 1 "$file NO está protegido"
    fi
done

echo ""

# 4. Verificar documentación
echo -e "${CYAN}4. Documentación:${NC}"
test -f docs/bewpro/new-project.md
print_check $? "docs/bewpro/new-project.md existe"

test -f docs/cd-system/proteccion-archivos-sistema.md
print_check $? "docs/cd-system/proteccion-archivos-sistema.md existe"

test -f docs/cd-system/flujo-cambios-core-proyectos.md
print_check $? "docs/cd-system/flujo-cambios-core-proyectos.md existe"

echo ""

# 5. Verificar estructura del proyecto
echo -e "${CYAN}5. Estructura del Proyecto:${NC}"
test -f composer.json
print_check $? "composer.json existe"

test -f artisan
print_check $? "artisan existe"

test -d app
print_check $? "directorio app/ existe"

test -d config
print_check $? "directorio config/ existe"

test -f config/cd-system.php
print_check $? "config/cd-system.php existe"

test -f config/site.php
print_check $? "config/site.php existe"

echo ""

# 6. Verificar Git
echo -e "${CYAN}6. Estado de Git:${NC}"
if git rev-parse --git-dir > /dev/null 2>&1; then
    print_check 0 "Repositorio Git inicializado"

    CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
    if [ "$CURRENT_BRANCH" == "cd-system" ]; then
        print_check 0 "Estás en la rama cd-system"
    else
        print_warning "Estás en la rama: $CURRENT_BRANCH (esperado: cd-system)"
    fi

    if git remote | grep -q "origin"; then
        ORIGIN_URL=$(git remote get-url origin)
        print_check 0 "Remote origin configurado: $ORIGIN_URL"
    else
        print_check 1 "Remote origin no configurado"
    fi
else
    print_check 1 "No es un repositorio Git"
fi

echo ""

# 7. Verificar dependencias del sistema
echo -e "${CYAN}7. Dependencias del Sistema:${NC}"
if command -v git &> /dev/null; then
    print_check 0 "Git instalado"
else
    print_check 1 "Git NO instalado"
fi

if command -v composer &> /dev/null; then
    print_check 0 "Composer instalado"
else
    print_check 1 "Composer NO instalado"
fi

if command -v php &> /dev/null; then
    PHP_VERSION=$(php -v | head -1)
    print_check 0 "PHP instalado: $PHP_VERSION"
else
    print_check 1 "PHP NO instalado"
fi

echo ""

# Resumen
print_header "Resumen de Verificación"
echo -e "${GREEN}Verificaciones exitosas: $PASSED${NC}"
if [ $FAILED -gt 0 ]; then
    echo -e "${RED}Verificaciones fallidas: $FAILED${NC}"
    echo ""
    echo -e "${YELLOW}⚠️  Por favor, corrige los errores antes de crear nuevos proyectos${NC}"
    exit 1
else
    echo -e "${GREEN}✅ Todas las verificaciones pasaron${NC}"
    echo ""
    echo -e "${CYAN}El sistema está listo para crear nuevos proyectos${NC}"
    echo ""
    echo -e "${BLUE}Para crear un nuevo proyecto, ejecuta:${NC}"
    echo -e "${GREEN}./scripts/create-new-project.sh${NC}"
    exit 0
fi

