#!/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 "assets/Time" ]; then
    TIME_SRC="assets/Time"
elif [ -d "target/data/panel/Time" ]; then
    TIME_SRC="target/data/panel/Time"
else
    echo "ERROR: carpeta 'Time' no encontrada (se buscó en assets/Time y target/data/panel/Time)"
    exit 1
fi
mkdir -p "$HOME/.gradio/data/panel"
cp -r "$TIME_SRC" "$HOME/.gradio/data/panel/Time"

# ── Instalar contexto de IA (opencode) ───────────────────────────────────────
OPENCODE_CTX_SRC=""
if [ -d "assets/opencode" ]; then
    OPENCODE_CTX_SRC="assets/opencode"
elif [ -d "target/data/opencode" ]; then
    OPENCODE_CTX_SRC="target/data/opencode"
fi
if [ -n "$OPENCODE_CTX_SRC" ]; then
    echo "==> Instalando contexto IA en ~/.gradio/data/opencode/..."
    mkdir -p "$HOME/.gradio/data/opencode/agents"
    mkdir -p "$HOME/.gradio/data/opencode/context"
    cp -r "$OPENCODE_CTX_SRC/"* "$HOME/.gradio/data/opencode/" 2>/dev/null || true
fi

# ── Instalar skins de ejemplo ──────────────────────────────────────────────────
# Solo copia skins que aún no existan en destino, para no pisar los que el
# usuario haya instalado/personalizado en una reinstalación o actualización.
SKINS_SRC=""
if [ -d "assets/skins" ]; then
    SKINS_SRC="assets/skins"
elif [ -d "target/data/skins" ]; then
    SKINS_SRC="target/data/skins"
fi
if [ -n "$SKINS_SRC" ]; then
    echo "==> Instalando skins de ejemplo en ~/.gradio/data/skins/..."
    mkdir -p "$HOME/.gradio/data/skins"
    for skin_dir in "$SKINS_SRC"/*/; do
        [ -d "$skin_dir" ] || continue
        skin_name=$(basename "$skin_dir")
        if [ ! -d "$HOME/.gradio/data/skins/$skin_name" ]; then
            cp -r "$skin_dir" "$HOME/.gradio/data/skins/$skin_name"
        fi
    done
fi

# ── 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"
# Limpiar entrada de versiones antiguas (nombre no coincidía con el app_id)
rm -f "$DESKTOP_DIR/gradio-player.desktop"
cat > "$DESKTOP_DIR/com.gradio.radio-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"
