#!/bin/bash
# =====================================================================
# FileBot Docker Auto-Renamer v12
# - Renomme le dossier et tous les fichiers in-place
# - Respecte les langues FR/ES/IT/NL
# - --force-artwork pour artworks anglais sur autres films
# - Corrige les permissions après renommage
# =====================================================================

set -euo pipefail

DOCKER_IMAGE="rednoah/filebot"
MEDIA_BASE="/mnt/union"
LICENSE_FILE="/media/shared/home/dbi/FileBot_License_PX76319004.psm"
DATA_DIR="/opt/filebot_data"
TMP_LOG="/tmp/filebot_rename.log"
DEFAULT_UID=1000
DEFAULT_GID=$(getent group fs_data | cut -d: -f3 || echo 1000)

ACTION="move"        # move | copy | test
DRYRUN="false"
INTERACTIVE="false"
REPORT="false"
FORCE_ARTWORK="false"
REPORT_FILE="${DATA_DIR}/filebot_report_$(date +%Y%m%d).txt"

log() { echo -e "[$(date '+%F %T')] $*" | tee -a "$TMP_LOG"; }

install_license() {
  if [[ ! -f "$DATA_DIR/license.txt" ]]; then
    log "🪪 Installation de la licence FileBot..."
    mkdir -p "$DATA_DIR"
    docker run --rm \
      -v "$DATA_DIR:/data" \
      -v "$LICENSE_FILE:/data/license.psm:ro" \
      -e PUID=0 -e PGID=0 \
      "$DOCKER_IMAGE" \
      filebot --license /data/license.psm || true
  else
    log "✅ Licence déjà installée."
  fi
}

# --- Détecte la langue originale du film via TMDb ---
get_original_lang() {
  local path="$1"
  docker run --rm \
    -e PUID=0 -e PGID=0 \
    -v "${MEDIA_BASE}:${MEDIA_BASE}" \
    -v "$DATA_DIR:/data" \
    "$DOCKER_IMAGE" \
    filebot -rename "$path" \
      --db TheMovieDB \
      --output /tmp \
      --action test \
      --format "{info.language}" 2>/dev/null \
    | grep -E '^[a-z]{2}$' | head -n1
}

confirm_action() {
  if [[ "$INTERACTIVE" == "true" ]]; then
    read -rp "Renommer maintenant ? [y/N] " reply
    [[ "$reply" =~ ^[Yy]$ ]] || { log "⏭️  Ignoré."; return 1; }
  fi
  return 0
}

run_filebot() {
  local path="$1"
  local original_lang lang_meta DB FORMAT OUT TYPE APPLY_OPT

  original_lang=$(get_original_lang "$path" || echo "en")

  # --- Détermine la langue des métadonnées et artworks ---
  case "$original_lang" in
    fr|fre|fra|es|spa|it|ita|nl|dut|nld)
      lang_meta="fr"
      APPLY_OPT="--apply artwork,nfo"
      ;;
    *)
      lang_meta="en"
      if [[ "$FORCE_ARTWORK" == "true" ]]; then
        APPLY_OPT="--apply artwork,nfo"
      else
        APPLY_OPT="--apply nfo"
      fi
      ;;
  esac

  # --- Format standard Plex/Emby/Jellyfin ---
  if [[ "$path" =~ [Ss][0-9]+[Ee][0-9]+ ]]; then
    DB="TheTVDB"
    FORMAT="{n}/Season {s.pad(2)}/{n} - S{s.pad(2)}E{e.pad(2)} - {t} - {vf}{' ' + vc ?: ''}{' ' + ac ?: ''}{' - ' + group ?: ''}"
    TYPE="série"
  else
    DB="TheMovieDB"
    FORMAT="{n} ({y})/{n} ({y}) - {vf}{' ' + vc ?: ''}{' ' + ac ?: ''}{' - ' + group ?: ''}"
    TYPE="film"
  fi

  log "➡️  Traitement du $TYPE : $path"
  log "🌐 Langue d'origine détectée : ${original_lang:-inconnue}"
  log "🗂️  Métadonnées : $lang_meta"
  log "🖼️  Artwork : $([[ "$APPLY_OPT" == *artwork* ]] && echo 'activé' || echo 'désactivé')"

  confirm_action || return 0

  # --- Exécution principale FileBot ---
  docker run --rm \
    -e PUID=0 -e PGID=0 \
    -v "${MEDIA_BASE}:${MEDIA_BASE}" \
    -v "$DATA_DIR:/data" \
    "$DOCKER_IMAGE" \
    filebot -rename "$path" \
      --db "$DB" \
      --lang "$lang_meta" \
      --action "$ACTION" \
      --conflict override \
      --output "$MEDIA_BASE" \
      --format "$FORMAT"

  # --- Post-processing séparé (artwork, nfo, etc.) ---
  # --- Téléchargement des artworks (sur base des fichiers vidéo seulement) ---
  # --- Post-processing (artwork & nfo) sur base des fichiers vidéo uniquement ---
  VIDEO_FILES=$(find "$path" -type f -iregex '.*\.\(mkv\|mp4\|avi\|mov\|m4v\)$')

  if [[ "$APPLY_OPT" == *"artwork"* ]]; then
    log "🎨 Téléchargement des artworks..."
    for f in $VIDEO_FILES; do
      docker run --rm \
        -e PUID=0 -e PGID=0 \
        -e HOME=/data \
        -v "${MEDIA_BASE}:${MEDIA_BASE}" \
        -v "$DATA_DIR:/data" \
        "$DOCKER_IMAGE" \
        filebot -script fn:artwork.tmdb "$f" --output "$MEDIA_BASE" \
        || log "⚠️ Artwork non généré pour $f"
    done
  fi

  if [[ "$APPLY_OPT" == *"nfo"* ]]; then
    log "🧾 Génération des fichiers NFO..."
    for f in $VIDEO_FILES; do
      docker run --rm \
        -e PUID=0 -e PGID=0 \
        -e HOME=/data \
        -v "${MEDIA_BASE}:${MEDIA_BASE}" \
        -v "$DATA_DIR:/data" \
        "$DOCKER_IMAGE" \
        filebot -script fn:nfo "$f" --output "$MEDIA_BASE" \
        || log "⚠️ NFO non généré pour $f"
    done
  fi






  # --- Renomme le dossier source lui-même ---
  local base_name new_name
  base_name=$(basename "$path")
  new_name=$(docker run --rm \
      -v "${MEDIA_BASE}:${MEDIA_BASE}" \
      -v "$DATA_DIR:/data" \
      "$DOCKER_IMAGE" \
      filebot -rename "$path" \
        --db "$DB" \
        --output /tmp \
        --action test \
        --format "{n} ({y})" 2>/dev/null | grep -v '/')

  if [[ -n "$new_name" && "$base_name" != "$new_name" ]]; then
    local parent_dir
    parent_dir=$(dirname "$path")
    mv -v "$path" "${parent_dir}/${new_name}" | tee -a "$TMP_LOG"
    path="${parent_dir}/${new_name}"
  fi

  # --- Nettoyage et permissions ---
  find "$MEDIA_BASE" -mindepth 1 -type d -empty -delete
  chown -R "$DEFAULT_UID:$DEFAULT_GID" "$path" || true
  log "✅ Permissions corrigées sur $path"
}

usage() {
  echo "Usage: $0 [--auto] [--test] [--interactive] [--report] [--force-artwork] [<fichier|dossier|liste.txt>]"
  exit 1
}

# -------- Lecture des arguments --------
[[ $# -lt 1 ]] && usage
ARGS=("$@")
AUTO="false"

for arg in "${ARGS[@]}"; do
  case "$arg" in
    --test) ACTION="test"; DRYRUN="true" ;;
    --auto) AUTO="true" ;;
    --interactive) INTERACTIVE="true" ;;
    --report) REPORT="true" ;;
    --force-artwork) FORCE_ARTWORK="true" ;;
    *) INPUT="$arg" ;;
  esac
done

log "=== Démarrage de FileBot Rename (in-place rename + fix perms) ==="
install_license

# -------- Mode manuel --------
if [[ -z "${INPUT:-}" ]]; then
  usage
elif [[ -f "$INPUT" && "$INPUT" == *.txt ]]; then
  log "📄 Liste détectée : $INPUT"
  while read -r line; do
    [[ -z "$line" || "$line" =~ ^# ]] && continue
    run_filebot "$line"
  done < "$INPUT"
elif [[ -e "$INPUT" ]]; then
  run_filebot "$INPUT"
else
  log "❌ Fichier ou dossier non trouvé : $INPUT"
  exit 1
fi

log "✅ Traitement terminé"
