#!/usr/bin/env bash
# ==============================================================================
# Script de Inicialización / Limpieza de Base de Datos para Servidor Linux
# IoPlay DCM - Visor e Indexador de Documentos
# ==============================================================================
# Uso:
#   ./reset_db.sh                  # Modo interactivo (pregunta confirmación)
#   ./reset_db.sh -f               # Modo forzado (sin confirmación)
#   ./reset_db.sh -f -r            # Modo forzado + Indexación inmediata
#   ./reset_db.sh --reindex        # Limpia e indexa
#   ./reset_db.sh --clean-files    # Borra físicamente archivos .db, .db-wal, .db-shm
# ==============================================================================

set -e

# Directorio base del script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

CONTAINER_NAME="ioplay-dcm"
DATA_DIR="$SCRIPT_DIR/data"
DB_FILE="$DATA_DIR/facturas_index.db"

# Colores para salida de consola
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # Sin color

echo -e "${BLUE}==============================================================================${NC}"
echo -e "${CYAN}      IoPlay DCM - Inicializador de BDD (Servidor Linux)                      ${NC}"
echo -e "${BLUE}==============================================================================${NC}"

# Procesar argumentos especiales de bash
CLEAN_FILES=false
PASSTHROUGH_ARGS=()

for arg in "$@"; do
    case $arg in
        --clean-files)
            CLEAN_FILES=true
            ;;
        *)
            PASSTHROUGH_ARGS+=("$arg")
            ;;
    esac
done

# Opción 1: Borrado físico directo de archivos SQLite
if [ "$CLEAN_FILES" = true ]; then
    echo -e "${YELLOW}[!] Modo --clean-files activado: Eliminando archivos físicos de base de datos...${NC}"
    
    # Detener contenedor si está corriendo para evitar locks
    if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        echo -e "${YELLOW}[*] Pausando contenedor Docker $CONTAINER_NAME temporalmente...${NC}"
        docker stop "$CONTAINER_NAME" >/dev/null 2>&1 || true
        DOCKER_WAS_STOPPED=true
    fi

    rm -f "$DB_FILE" "$DB_FILE-wal" "$DB_FILE-shm"
    echo -e "${GREEN}[✓] Archivos SQLite eliminados.${NC}"

    if [ "${DOCKER_WAS_STOPPED:-false}" = true ]; then
        echo -e "${YELLOW}[*] Reiniciando contenedor Docker...${NC}"
        docker start "$CONTAINER_NAME" >/dev/null 2>&1 || true
    fi

    echo -e "${GREEN}[✓] Base de datos limpia y lista para nueva indexación.${NC}"
    exit 0
fi

# Opción 2: Ejecución mediante Docker o Python local
if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${GREEN}[*] Detectado contenedor Docker activo: ${CONTAINER_NAME}${NC}"
    echo -e "${CYAN}[*] Ejecutando reset_db.py dentro del contenedor...${NC}\n"
    
    # Si la terminal es interactiva usamos -t, sino solo -i
    DOCKER_FLAGS="-i"
    if [ -t 0 ]; then
        DOCKER_FLAGS="-it"
    fi

    docker exec $DOCKER_FLAGS "$CONTAINER_NAME" python reset_db.py "${PASSTHROUGH_ARGS[@]}"
else
    echo -e "${YELLOW}[*] Contenedor Docker no detectado en ejecución. Ejecutando en entorno local Python...${NC}\n"
    
    # Determinar comando de python disponible
    if command -v python3 >/dev/null 2>&1; then
        PYTHON_CMD="python3"
    elif command -v python >/dev/null 2>&1; then
        PYTHON_CMD="python"
    else
        echo -e "${RED}[ERROR] No se encontró Python 3 ni Docker en el sistema.${NC}"
        exit 1
    fi

    $PYTHON_CMD reset_db.py "${PASSTHROUGH_ARGS[@]}"
fi
