#!/bin/bash
#
# Script de limpieza de artefactos generados
# Uso: ./scripts/clean.sh [-a|--all] [-h|--help]
#
# Elimina:
# - Build outputs (.next/, dist/, build/)
# - Dependencias (node_modules/)
# - Logs, coverage, archivos temporales
#

set -euo pipefail

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

# Flags
ALL=false
DRY_RUN=false

# Función para mostrar ayuda
show_help() {
    cat << EOF
Uso: ./scripts/clean.sh [OPCIONES]

Limpia artefactos generados del proyecto.

OPCIONES:
    -a, --all       Limpia TODO incluyendo node_modules
    -d, --dry-run   Muestra qué se eliminaría sin eliminarlo
    -h, --help      Muestra esta ayuda

Ejemplos:
    ./scripts/clean.sh              # Limpia builds, logs, coverage
    ./scripts/clean.sh -a            # Limpia TODO incluyendo node_modules
    ./scripts/clean.sh -d            # Muestra qué se eliminaría

EOF
}

# Parsear argumentos
while [[ $# -gt 0 ]]; do
    case $1 in
        -a|--all)
            ALL=true
            shift
            ;;
        -d|--dry-run)
            DRY_RUN=true
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            echo -e "${RED}Error: Opción desconocida: $1${NC}"
            echo "Usa -h o --help para ver opciones disponibles"
            exit 1
            ;;
    esac
done

# Función para eliminar directorios
remove_dir() {
    local path=$1
    if [[ -d "$path" ]]; then
        if [[ "$DRY_RUN" == true ]]; then
            echo -e "${YELLOW}[DRY RUN] Se eliminaría:${NC} $path"
            return 0
        fi
        
        # Calcular tamaño
        local size
        size=$(du -sh "$path" 2>/dev/null | cut -f1) || size="?"
        rm -rf "$path"
        echo -e "${GREEN}✓${NC} Eliminado: $path (${size})"
        return 0
    fi
    return 1
}

# Función para eliminar archivos
remove_file() {
    local pattern=$1
    if [[ "$DRY_RUN" == true ]]; then
        find . -name "$pattern" -type f 2>/dev/null | while read -r file; do
            echo -e "${YELLOW}[DRY RUN] Se eliminaría:${NC} $file"
        done
        return 0
    fi
    
    local count=0
    while IFS= read -r -d '' file; do
        rm -f "$file"
        ((count++))
    done < <(find . -name "$pattern" -type f -print0 2>/dev/null)
    
    if [[ $count -gt 0 ]]; then
        echo -e "${GREEN}✓${NC} Eliminados $count archivos: $pattern"
    fi
}

# Header
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Limpieza de Artefactos Generados     ${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

if [[ "$DRY_RUN" == true ]]; then
    echo -e "${YELLOW}MODO DRY RUN - No se eliminará nada${NC}"
    echo ""
fi

# Contador de eliminados
declare -i TOTAL_SIZE=0

# ============================================
# FRONTEND - Build outputs
# ============================================
echo -e "${BLUE}Frontend:${NC}"
remove_dir "frontend/.next"
remove_dir "frontend/out"
remove_dir "frontend/build"
remove_dir "frontend/dist"

# ============================================
# BACKEND - Build outputs
# ============================================
echo ""
echo -e "${BLUE}Backend:${NC}"
remove_dir "backend/dist"
remove_dir "backend/build"
remove_dir "backend/coverage"
remove_dir "backend/.nyc_output"

# ============================================
# ROOT - Build outputs
# ============================================
echo ""
echo -e "${BLUE}Root:${NC}"
remove_dir "coverage"
remove_dir ".nyc_output"
remove_dir ".cache"
remove_dir ".temp"
remove_dir ".tmp"

# ============================================
# LOGS
# ============================================
echo ""
echo -e "${BLUE}Logs:${NC}"
remove_file "*.log"
remove_file "npm-debug.log*"
remove_file "yarn-debug.log*"
remove_file "yarn-error.log*"

# ============================================
# COVERAGE REPORTS
# ============================================
echo ""
echo -e "${BLUE}Coverage:${NC}"
remove_dir "coverage"
remove_file "*.lcov"

# ============================================
# NODE_MODULES (solo si --all)
# ============================================
if [[ "$ALL" == true ]]; then
    echo ""
    echo -e "${BLUE}Dependencias (node_modules):${NC}"
    remove_dir "frontend/node_modules"
    remove_dir "backend/node_modules"
    remove_dir "node_modules"
    
    echo ""
    echo -e "${YELLOW}Para reinstalar dependencias:${NC}"
    echo "  npm install"
    echo "  cd frontend && npm install"
    echo "  cd ../backend && npm install"
fi

# ============================================
# DOCKER DATA (opcional)
# ============================================
echo ""
echo -e "${BLUE}Docker data (si existen):${NC}"
remove_dir "docker-data"
remove_dir "postgres_data"
remove_dir "redis_data"

# ============================================
# OTROS ARTEFACTOS
# ============================================
echo ""
echo -e "${BLUE}Otros artefactos:${NC}"
remove_file ".DS_Store"
remove_file "Thumbs.db"
remove_file "*.swp"
remove_file "*.swo"
remove_file "*~"
remove_dir "uploads"  # Excepto .gitkeep

# Preservar .gitkeep en uploads
if [[ -d "uploads" && "$DRY_RUN" == false ]]; then
    mkdir -p uploads/pdfs
    touch uploads/pdfs/.gitkeep
    echo -e "${GREEN}✓${NC} Preservado uploads/pdfs/.gitkeep"
fi

# ============================================
# RESUMEN
# ============================================
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}Limpieza completada!${NC}"
echo -e "${BLUE}========================================${NC}"

if [[ "$DRY_RUN" == true ]]; then
    echo ""
    echo -e "${YELLOW}Nota:${NC} Esto fue un DRY RUN. Nada fue eliminado."
    echo "Ejecuta sin --dry-run para limpiar realmente."
fi

if [[ "$ALL" == true ]]; then
    echo ""
    echo -e "${YELLOW}Nota:${NC} Se eliminaron node_modules."
    echo "Ejecuta 'npm install' para reinstalar dependencias."
fi

echo ""
echo -e "${BLUE}Para reinstalar dependencias:${NC}"
echo "  npm install"
echo "  cd frontend && npm install  && cd ../backend && npm install"
