#!/bin/bash
# ─── G Radio Player — instalador del sistema ─────────────────────────────────
set -e
cd "$(dirname "$0")"

INSTALL_DIR="$HOME/.local/share/radio-player"
BIN_DIR="$HOME/.local/bin"
DESKTOP_DIR="$HOME/.local/share/applications"

# ── 1. Verificar dependencias del sistema ─────────────────────────────────────
echo "==> Verificando dependencias..."
MISSING=()

check() {
    if ! dpkg -l "$1" &>/dev/null 2>&1 && ! rpm -q "$1" &>/dev/null 2>&1; then
        MISSING+=("$1")
    fi
}

# Detectar gestor de paquetes
if command -v apt &>/dev/null; then
    PKG_MGR="apt"
    PKGS=(
        gstreamer1.0-plugins-base
        gstreamer1.0-plugins-good
        gstreamer1.0-plugins-bad
        gstreamer1.0-plugins-ugly
        gstreamer1.0-libav
        gstreamer1.0-pulseaudio
        gstreamer1.0-alsa
        libgstreamer1.0-0
        libgstreamer-plugins-base1.0-0
        ffmpeg
    )
    MISSING_CHECK=$(dpkg -l "${PKGS[@]}" 2>&1 | grep "^un\|no packages" | awk '{print $2}' || true)
elif command -v dnf &>/dev/null; then
    PKG_MGR="dnf"
    PKGS=(
        gstreamer1-plugins-base
        gstreamer1-plugins-good
        gstreamer1-plugins-bad-free
        gstreamer1-plugins-ugly-free
        gstreamer1-libav
        ffmpeg
    )
else
    PKG_MGR="unknown"
    PKGS=()
fi

if [ ${#PKGS[@]} -gt 0 ] && [ -n "$MISSING_CHECK" ]; then
    echo ""
    echo "  Faltan dependencias GStreamer. Instalando..."
    if [ "$PKG_MGR" = "apt" ]; then
        sudo apt install -y "${PKGS[@]}"
    elif [ "$PKG_MGR" = "dnf" ]; then
        sudo dnf install -y "${PKGS[@]}"
    fi
fi

# Verificar ffmpeg/ffprobe
if ! command -v ffprobe &>/dev/null; then
    echo "  ffprobe no encontrado. Instalando ffmpeg..."
    if [ "$PKG_MGR" = "apt" ]; then
        sudo apt install -y ffmpeg
    elif [ "$PKG_MGR" = "dnf" ]; then
        sudo dnf install -y ffmpeg
    else
        echo "  AVISO: instala ffmpeg manualmente (necesario para playlist-refill)"
    fi
fi

# ── 2. Instalar binarios ──────────────────────────────────────────────────────
echo "==> Instalando binarios en $BIN_DIR..."
BINS=(
    radio-player
    comercial-scheduler
    playlist-refill
    gr-visor
    gr-botonera
    gr-buscador
    gr-parrilla
    gr-pautaje
    gr-playlist
    gr-record
    gr-reportes
)
for bin in "${BINS[@]}"; do
    if [ ! -f "target/release/$bin" ]; then
        echo "ERROR: binario no encontrado: target/release/$bin"
        echo "       Compila el proyecto antes de instalar (cargo build --release)"
        exit 1
    fi
done
mkdir -p "$BIN_DIR"
for bin in "${BINS[@]}"; do
    cp "target/release/$bin" "$BIN_DIR/$bin"
    chmod +x "$BIN_DIR/$bin"
done

# ── 3. Instalar assets ───────────────────────────────────────────────────────
echo "==> Instalando assets..."
if [ ! -d "target/data/panel/Time" ]; then
    echo "ERROR: carpeta 'target/data/panel/Time' no encontrada en el paquete de instalación"
    exit 1
fi
mkdir -p "$HOME/.gradio/data/panel"
cp -r target/data/panel/Time "$HOME/.gradio/data/panel/Time"

# ── 4. Crear lanzador principal ───────────────────────────────────────────────
echo "==> Creando lanzador..."
mkdir -p "$INSTALL_DIR"
cat > "$INSTALL_DIR/gradio.sh" << 'LAUNCHER'
#!/bin/bash
BIN="$HOME/.local/bin"

# Crear directorios de configuración
mkdir -p "$HOME/.gradio/data/tmp"
mkdir -p "$HOME/.gradio/data/parrilla"
mkdir -p "$HOME/.gradio/data/comerciales"
mkdir -p "$HOME/.gradio/data/eventos-espera"
mkdir -p "$HOME/.gradio/data/eventos"
mkdir -p "$HOME/.gradio/data/reporte"
mkdir -p "$HOME/G Radio/inicio-espacio-pub"
mkdir -p "$HOME/G Radio/fin-espacio-pub"

# Iniciar auxiliares
"$BIN/comercial-scheduler" &
SCHED_PID=$!
"$BIN/playlist-refill" &
REFILL_PID=$!

# Iniciar UI
"$BIN/radio-player" "$@"
EXIT_CODE=$?

# Apagar auxiliares
kill $SCHED_PID $REFILL_PID 2>/dev/null
wait $SCHED_PID $REFILL_PID 2>/dev/null
exit $EXIT_CODE
LAUNCHER
chmod +x "$INSTALL_DIR/gradio.sh"
ln -sf "$INSTALL_DIR/gradio.sh" "$BIN_DIR/gradio"

# ── 5. Entrada de menú de escritorio ─────────────────────────────────────────
echo "==> Registrando en el menú de aplicaciones..."
mkdir -p "$DESKTOP_DIR"
cat > "$DESKTOP_DIR/gradio-player.desktop" << DESKTOP
[Desktop Entry]
Type=Application
Name=G Radio Player
GenericName=Radio Player
Comment=Reproductor de radio profesional
Exec=$INSTALL_DIR/gradio.sh
Icon=gradio-player
Categories=AudioVideo;Audio;Player;
Terminal=false
StartupNotify=true
DESKTOP

# Actualizar base de datos de aplicaciones
update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true

# ── 6. Agregar ~/.local/bin al PATH si no está ────────────────────────────────
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    echo ""
    echo "  AVISO: $HOME/.local/bin no está en tu PATH."
    echo "  Agrega esta línea a tu ~/.bashrc o ~/.zshrc:"
    echo ""
    echo '    export PATH="$HOME/.local/bin:$PATH"'
    echo ""
fi

echo ""
echo "✅  Instalación completa."
echo ""
echo "  Ejecutar desde terminal:  $INSTALL_DIR/gradio.sh"
echo "  Ejecutar desde el menú:   busca 'G Radio Player'"
echo ""
echo "  Para desinstalar:  ./uninstall.sh"
