#!/bin/bash
# =============================================================================
# sync-to-deploy-repos.sh
#
# Script para sincronizar componentes del workspace a repositorios de deploy
# independientes para CI/CD con Jenkins
#
# Uso:
#   ./sync-to-deploy-repos.sh [vertical] [componente]
#   ./sync-to-deploy-repos.sh construccion backend
#   ./sync-to-deploy-repos.sh construccion all
#   ./sync-to-deploy-repos.sh all all
#
# Autor: Architecture-Analyst
# Fecha: 2025-12-12
# =============================================================================

set -e

# -----------------------------------------------------------------------------
# CONFIGURACION
# -----------------------------------------------------------------------------

WORKSPACE_ROOT="/home/isem/workspace/projects/erp-suite"
DEPLOY_REPOS_ROOT="/home/isem/deploy-repos"

# Configuración de Gitea (usar token en lugar de password para evitar bloqueos)
GITEA_HOST="72.60.226.4:3000"
GITEA_USER="rckrdmrd"
GITEA_TOKEN="3fb69a2465f4c1d43c856e980236fbc9f79278b1"

# Verticales disponibles
VERTICALES=("construccion" "mecanicas-diesel" "vidrio-templado" "retail" "clinicas")

# Proyectos especiales (no en verticales/)
PROYECTOS_ESPECIALES=("erp-core")

# Componentes por vertical
COMPONENTES=("backend" "frontend-web" "frontend-mobile" "database")

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

# -----------------------------------------------------------------------------
# FUNCIONES
# -----------------------------------------------------------------------------

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[OK]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

# Crear repo de deploy si no existe
ensure_deploy_repo() {
    local repo_path="$1"
    local repo_name="$2"

    if [ ! -d "$repo_path" ]; then
        log_info "Creando repo de deploy: $repo_name"
        mkdir -p "$repo_path"
        cd "$repo_path"
        git init -b main
        echo "# $repo_name" > README.md
        echo "Repositorio de deploy para CI/CD con Jenkins" >> README.md
        git add README.md
        git commit -m "Initial commit - Deploy repo for $repo_name"

        # Configurar remoto con token
        git remote add origin "http://${GITEA_USER}:${GITEA_TOKEN}@${GITEA_HOST}/${GITEA_USER}/${repo_name}.git"
        log_success "Repo creado: $repo_path"
    else
        # Asegurar que el remoto use token
        cd "$repo_path"
        git remote set-url origin "http://${GITEA_USER}:${GITEA_TOKEN}@${GITEA_HOST}/${GITEA_USER}/${repo_name}.git" 2>/dev/null || \
        git remote add origin "http://${GITEA_USER}:${GITEA_TOKEN}@${GITEA_HOST}/${GITEA_USER}/${repo_name}.git" 2>/dev/null
    fi
}

# Sincronizar un componente
sync_component() {
    local vertical="$1"
    local component="$2"

    local source_path=""
    # Evitar duplicar prefijo "erp-" si el proyecto ya lo tiene
    local repo_name=""
    if [[ "$vertical" == erp-* ]]; then
        repo_name="${vertical}-${component}"
    else
        repo_name="erp-${vertical}-${component}"
    fi
    local repo_path="${DEPLOY_REPOS_ROOT}/${repo_name}"

    # Determinar base path (verticales/ o directamente en apps/)
    local base_path=""
    if [[ " ${PROYECTOS_ESPECIALES[*]} " =~ " ${vertical} " ]]; then
        base_path="${WORKSPACE_ROOT}/apps/${vertical}"
    else
        base_path="${WORKSPACE_ROOT}/apps/verticales/${vertical}"
    fi

    # Determinar ruta fuente según componente
    case "$component" in
        "backend")
            source_path="${base_path}/backend"
            ;;
        "frontend-web")
            # Soportar ambas estructuras: frontend/web/ o frontend/ directo
            if [ -d "${base_path}/frontend/web" ]; then
                source_path="${base_path}/frontend/web"
            elif [ -d "${base_path}/frontend" ] && [ -f "${base_path}/frontend/package.json" ]; then
                source_path="${base_path}/frontend"
            else
                source_path="${base_path}/frontend/web"
            fi
            ;;
        "frontend-mobile")
            source_path="${base_path}/frontend/mobile"
            ;;
        "database")
            source_path="${base_path}/database"
            ;;
        *)
            log_error "Componente desconocido: $component"
            return 1
            ;;
    esac

    # Verificar que existe el source
    if [ ! -d "$source_path" ]; then
        log_warn "Source no existe: $source_path"
        return 0
    fi

    # Crear repo si no existe
    ensure_deploy_repo "$repo_path" "$repo_name"

    # Sincronizar usando rsync
    log_info "Sincronizando: $source_path -> $repo_path"

    rsync -av --delete \
        --exclude 'node_modules' \
        --exclude 'dist' \
        --exclude '.env' \
        --exclude '.env.local' \
        --exclude '*.log' \
        --exclude '.DS_Store' \
        --exclude 'coverage' \
        --exclude '.nyc_output' \
        "$source_path/" "$repo_path/"

    # Crear .gitignore si no existe
    if [ ! -f "$repo_path/.gitignore" ]; then
        cat > "$repo_path/.gitignore" << 'EOF'
# Dependencies
node_modules/

# Build output
dist/
build/

# Environment files (local)
.env
.env.local
.env.*.local

# IDE
.idea/
.vscode/
*.swp
*.swo

# Logs
*.log
npm-debug.log*

# Coverage
coverage/
.nyc_output/

# OS
.DS_Store
Thumbs.db

# Cache
.cache/
.parcel-cache/
EOF
    fi

    log_success "Sincronizado: $repo_name"
}

# Sincronizar todos los componentes de una vertical
sync_vertical() {
    local vertical="$1"

    log_info "=========================================="
    log_info "Sincronizando vertical: $vertical"
    log_info "=========================================="

    for component in "${COMPONENTES[@]}"; do
        sync_component "$vertical" "$component"
    done
}

# Mostrar uso
show_usage() {
    echo "Uso: $0 [proyecto] [componente]"
    echo ""
    echo "Proyectos disponibles:"
    for v in "${VERTICALES[@]}"; do
        echo "  - $v"
    done
    for p in "${PROYECTOS_ESPECIALES[@]}"; do
        echo "  - $p"
    done
    echo "  - all (todos los proyectos)"
    echo ""
    echo "Componentes disponibles:"
    for c in "${COMPONENTES[@]}"; do
        echo "  - $c"
    done
    echo "  - all (todos los componentes)"
    echo ""
    echo "Ejemplos:"
    echo "  $0 construccion backend      # Solo backend de construccion"
    echo "  $0 construccion all          # Todos los componentes de construccion"
    echo "  $0 erp-core backend          # Solo backend de erp-core"
    echo "  $0 all all                   # Todo el proyecto"
}

# -----------------------------------------------------------------------------
# MAIN
# -----------------------------------------------------------------------------

main() {
    local vertical="${1:-}"
    local component="${2:-}"

    if [ -z "$vertical" ] || [ -z "$component" ]; then
        show_usage
        exit 1
    fi

    # Crear directorio base de repos si no existe
    mkdir -p "$DEPLOY_REPOS_ROOT"

    log_info "Workspace: $WORKSPACE_ROOT"
    log_info "Deploy repos: $DEPLOY_REPOS_ROOT"
    echo ""

    # Procesar según parámetros
    if [ "$vertical" == "all" ]; then
        # Procesar verticales
        for v in "${VERTICALES[@]}"; do
            if [ "$component" == "all" ]; then
                sync_vertical "$v"
            else
                sync_component "$v" "$component"
            fi
        done
        # Procesar proyectos especiales
        for p in "${PROYECTOS_ESPECIALES[@]}"; do
            if [ "$component" == "all" ]; then
                sync_vertical "$p"
            else
                sync_component "$p" "$component"
            fi
        done
    else
        if [ "$component" == "all" ]; then
            sync_vertical "$vertical"
        else
            sync_component "$vertical" "$component"
        fi
    fi

    echo ""
    log_success "=========================================="
    log_success "Sincronizacion completada!"
    log_success "=========================================="
    echo ""
    log_info "Repos de deploy en: $DEPLOY_REPOS_ROOT"
    log_info "Para hacer push a remoto:"
    echo "  cd $DEPLOY_REPOS_ROOT/erp-{vertical}-{component}"
    echo "  git remote add origin git@github.com:isem-digital/erp-{vertical}-{component}.git"
    echo "  git push -u origin main"
}

main "$@"
