#!/bin/bash

BASE_DIR="/var/www/media/audios"

cd "$BASE_DIR" || exit 1

find . -type f -name "*.mp3" | while read -r filepath; do
    dir=$(dirname "$filepath")
    file=$(basename "$filepath")

    # Quitar extensión
    name="${file%.mp3}"

    # Convertir a ASCII (quita tildes)
    clean=$(echo "$name" | iconv -f UTF-8 -t ASCII//TRANSLIT)

    # Minúsculas
    clean=$(echo "$clean" | tr '[:upper:]' '[:lower:]')

    # Separar partes
    # Ej: 01_2 cronicas 01
    book_index=$(echo "$clean" | grep -oE '^[0-9]+')
    chapter=$(echo "$clean" | grep -oE '[0-9]+$')
    book_name=$(echo "$clean" | sed -E 's/^[0-9]+_//' | sed -E 's/[0-9]+$//')

    # Limpiar libro
    book_name=$(echo "$book_name" \
        | sed 's/  */ /g' \
        | sed 's/^ //;s/ $//' \
        | sed 's/ /-/g')

    # Normalizar números
    book_index=$(printf "%02d" "$book_index")
    chapter=$(printf "%02d" "$chapter")

    newname="${book_index}_${book_name}-${chapter}.mp3"

    if [[ "$file" != "$newname" ]]; then
        echo "✔ $file → $newname"
        mv -n "$filepath" "$dir/$newname"
    fi
done

echo "🔥 Renombrado global terminado"

