#!/bin/bash

###############################################################################
# 4Alarm - Script de Instalación y Configuración Inicial
# 
# Este script automatiza la instalación completa del sistema 4Alarm con
# todas las protecciones de seguridad y despliegue automatizado.
###############################################################################

set -e  # Salir si hay algún error

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

# Función para imprimir mensajes
print_header() {
    echo -e "\n${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║${NC}  $1"
    echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}\n"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

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

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# Verificar que estamos en el directorio correcto
if [ ! -f "package.json" ] || [ ! -d "frontend" ] || [ ! -d "backend" ]; then
    print_error "Este script debe ejecutarse desde el directorio raíz de 4alarm"
    exit 1
fi

print_header "4Alarm - Instalación Automatizada"

# ═══════════════════════════════════════════════════════════════
# PASO 1: Verificar dependencias del sistema
# ═══════════════════════════════════════════════════════════════

print_header "PASO 1: Verificando dependencias del sistema"

# Verificar Node.js
if ! command -v node &> /dev/null; then
    print_error "Node.js no está instalado"
    print_info "Instala Node.js desde: https://nodejs.org/"
    exit 1
fi
NODE_VERSION=$(node --version)
print_success "Node.js instalado: $NODE_VERSION"

# Verificar npm
if ! command -v npm &> /dev/null; then
    print_error "npm no está instalado"
    exit 1
fi
NPM_VERSION=$(npm --version)
print_success "npm instalado: $NPM_VERSION"

# Verificar Python
if ! command -v python3 &> /dev/null; then
    print_error "Python 3 no está instalado"
    exit 1
fi
PYTHON_VERSION=$(python3 --version)
print_success "Python instalado: $PYTHON_VERSION"

# Verificar pip
if ! command -v pip3 &> /dev/null; then
    print_error "pip3 no está instalado"
    exit 1
fi
print_success "pip3 instalado"

# Verificar git
if ! command -v git &> /dev/null; then
    print_warning "Git no está instalado (opcional para despliegues)"
else
    GIT_VERSION=$(git --version)
    print_success "Git instalado: $GIT_VERSION"
fi

# ═══════════════════════════════════════════════════════════════
# PASO 2: Instalar dependencias del servidor estático
# ═══════════════════════════════════════════════════════════════

print_header "PASO 2: Instalando dependencias del servidor estático"

print_info "Ejecutando: npm install"
npm install

if [ $? -eq 0 ]; then
    print_success "Dependencias del servidor estático instaladas"
else
    print_error "Error al instalar dependencias del servidor estático"
    exit 1
fi

# ═══════════════════════════════════════════════════════════════
# PASO 3: Instalar dependencias del frontend
# ═══════════════════════════════════════════════════════════════

print_header "PASO 3: Instalando dependencias del frontend"

cd frontend

print_info "Ejecutando: npm install"
npm install

if [ $? -eq 0 ]; then
    print_success "Dependencias del frontend instaladas"
else
    print_error "Error al instalar dependencias del frontend"
    exit 1
fi

cd ..

# ═══════════════════════════════════════════════════════════════
# PASO 4: Compilar el frontend
# ═══════════════════════════════════════════════════════════════

print_header "PASO 4: Compilando el frontend"

cd frontend

print_info "Ejecutando: npm run build"
npm run build

if [ $? -eq 0 ]; then
    print_success "Frontend compilado exitosamente"
    
    # Verificar que existe build/index.html
    if [ -f "build/index.html" ]; then
        print_success "Archivo build/index.html encontrado"
    else
        print_error "No se encontró build/index.html después de compilar"
        exit 1
    fi
else
    print_error "Error al compilar el frontend"
    exit 1
fi

cd ..

# ═══════════════════════════════════════════════════════════════
# PASO 5: Instalar dependencias del backend
# ═══════════════════════════════════════════════════════════════

print_header "PASO 5: Instalando dependencias del backend"

cd backend

print_info "Ejecutando: pip3 install -r requirements.txt"
pip3 install -r requirements.txt

if [ $? -eq 0 ]; then
    print_success "Dependencias del backend instaladas"
else
    print_error "Error al instalar dependencias del backend"
    exit 1
fi

cd ..

# ═══════════════════════════════════════════════════════════════
# PASO 6: Verificar archivo .env
# ═══════════════════════════════════════════════════════════════

print_header "PASO 6: Verificando configuración"

if [ ! -f "backend/.env" ]; then
    print_warning "No se encontró archivo backend/.env"
    print_info "Creando archivo .env de ejemplo..."
    
    cat > backend/.env << 'EOF'
# 4Alarm - Configuración del Backend
MONGO_URL=mongodb://localhost:27017
DB_NAME=4alarm
JWT_SECRET=change-this-secret-key-in-production
PORT=8000
EOF
    
    print_success "Archivo backend/.env creado"
    print_warning "IMPORTANTE: Edita backend/.env con tus credenciales reales"
else
    print_success "Archivo backend/.env encontrado"
fi

# ═══════════════════════════════════════════════════════════════
# PASO 7: Verificar PM2 (opcional)
# ═══════════════════════════════════════════════════════════════

print_header "PASO 7: Verificando PM2 (opcional)"

if ! command -v pm2 &> /dev/null; then
    print_warning "PM2 no está instalado"
    print_info "Para instalar PM2 globalmente: npm install -g pm2"
    print_info "PM2 es recomendado para producción pero no es obligatorio"
else
    PM2_VERSION=$(pm2 --version)
    print_success "PM2 instalado: $PM2_VERSION"
fi

# ═══════════════════════════════════════════════════════════════
# RESUMEN FINAL
# ═══════════════════════════════════════════════════════════════

print_header "✨ Instalación Completada Exitosamente"

echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║${NC}  Todos los componentes están instalados y listos     ${GREEN}║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"

echo ""
echo -e "${BLUE}📋 Próximos pasos:${NC}"
echo ""
echo -e "  ${YELLOW}1.${NC} Configurar backend/.env con tus credenciales"
echo -e "  ${YELLOW}2.${NC} Iniciar el backend FastAPI:"
echo -e "     ${GREEN}cd backend && uvicorn server:app --host 0.0.0.0 --port 8000${NC}"
echo ""
echo -e "  ${YELLOW}3.${NC} Iniciar el servidor estático (en otra terminal):"
echo -e "     ${GREEN}npm start${NC}"
echo -e "     o con PM2: ${GREEN}npm run pm2:start${NC}"
echo ""
echo -e "  ${YELLOW}4.${NC} Acceder a la aplicación:"
echo -e "     ${GREEN}http://localhost:3000${NC}"
echo ""
echo -e "${BLUE}📚 Documentación:${NC}"
echo -e "  Lee ${GREEN}DEPLOYMENT_GUIDE.md${NC} para más información"
echo ""
echo -e "${BLUE}🔒 Seguridad:${NC}"
echo -e "  ✓ Solo se sirve contenido compilado (build/)"
echo -e "  ✓ Archivos sensibles bloqueados (.env, .git, src/)"
echo -e "  ✓ Endpoint de despliegue automatizado: POST /api/deploy"
echo ""
echo -e "${GREEN}════════════════════════════════════════════════════════${NC}"
