#!/bin/bash
# Script de inicio rápido para desarrollo
# Combina las mejores estrategias: detección, paralelismo, SQLite

set -e

PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BACKEND_PORT=5000
FRONTEND_PORT=4200

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

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Verificar si un puerto está en uso
port_in_use() {
    lsof -i :$1 >/dev/null 2>&1
}

# Esperar a que un servicio esté listo
wait_for_service() {
    local url=$1
    local max_attempts=${2:-30}
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        if curl -s "$url" >/dev/null 2>&1; then
            return 0
        fi
        sleep 1
        ((attempt++))
    done
    return 1
}

# Iniciar Backend con SQLite (desarrollo rápido)
start_backend() {
    if port_in_use $BACKEND_PORT; then
        log_info "Backend ya corriendo en puerto $BACKEND_PORT"
        return 0
    fi

    log_info "Iniciando Backend (.NET) con SQLite..."
    cd "$PROJECT_ROOT/src/backend/Host"

    # Usar SQLite para desarrollo (sin necesidad de Docker/SQL Server)
    export ConnectionStrings__DefaultConnection="Data Source=$PROJECT_ROOT/data/dev.db"
    export ASPNETCORE_ENVIRONMENT=Development
    export USE_SQLITE=true

    nohup dotnet run --no-build > /tmp/backend.log 2>&1 &
    echo $! > /tmp/backend.pid

    log_info "Esperando Backend (max 20s)..."
    if wait_for_service "http://localhost:$BACKEND_PORT/health" 20; then
        log_info "Backend listo!"
        return 0
    else
        log_error "Backend no respondió a tiempo"
        return 1
    fi
}

# Iniciar Frontend
start_frontend() {
    if port_in_use $FRONTEND_PORT; then
        log_info "Frontend ya corriendo en puerto $FRONTEND_PORT"
        return 0
    fi

    log_info "Iniciando Frontend (Angular)..."
    cd "$PROJECT_ROOT/src/frontend"

    nohup npm start > /tmp/frontend.log 2>&1 &
    echo $! > /tmp/frontend.pid

    log_info "Esperando Frontend (max 30s)..."
    if wait_for_service "http://localhost:$FRONTEND_PORT" 30; then
        log_info "Frontend listo!"
        return 0
    else
        log_error "Frontend no respondió a tiempo"
        return 1
    fi
}

# Detener servicios
stop_services() {
    log_info "Deteniendo servicios..."
    [ -f /tmp/backend.pid ] && kill $(cat /tmp/backend.pid) 2>/dev/null && rm /tmp/backend.pid
    [ -f /tmp/frontend.pid ] && kill $(cat /tmp/frontend.pid) 2>/dev/null && rm /tmp/frontend.pid
    fuser -k $BACKEND_PORT/tcp 2>/dev/null || true
    fuser -k $FRONTEND_PORT/tcp 2>/dev/null || true
    log_info "Servicios detenidos"
}

# Main
case "${1:-start}" in
    start)
        log_info "=== Inicio Rápido de Desarrollo ==="

        # Crear directorio de datos si no existe
        mkdir -p "$PROJECT_ROOT/data"

        # Iniciar en paralelo
        start_backend &
        BACKEND_PID=$!

        start_frontend &
        FRONTEND_PID=$!

        # Esperar ambos
        wait $BACKEND_PID
        BACKEND_STATUS=$?

        wait $FRONTEND_PID
        FRONTEND_STATUS=$?

        if [ $BACKEND_STATUS -eq 0 ] && [ $FRONTEND_STATUS -eq 0 ]; then
            log_info "=== Todos los servicios listos ==="
            log_info "Backend:  http://localhost:$BACKEND_PORT/graphql"
            log_info "Frontend: http://localhost:$FRONTEND_PORT"
        else
            log_error "Algunos servicios fallaron"
            exit 1
        fi
        ;;
    stop)
        stop_services
        ;;
    restart)
        stop_services
        sleep 2
        $0 start
        ;;
    status)
        echo "Backend:  $(port_in_use $BACKEND_PORT && echo 'Running' || echo 'Stopped')"
        echo "Frontend: $(port_in_use $FRONTEND_PORT && echo 'Running' || echo 'Stopped')"
        ;;
    *)
        echo "Uso: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac
