#!/bin/bash
# =====================================================================
# FileBot Auto-Renamer v14 (bare-metal)
# - Utilise FileBot installé localement (pas Docker)
# - Traite /media/movies et /media/series
# - Renomme les fichiers et dossiers in-place
# - Gère les langues FR/ES/IT/NL/EN + option --force-artwork
# - Corrige les permissions à la fin
# =====================================================================

set -euo pipefail

MEDIA_MOVIES="/media/movies"
MEDIA_SERIES="/media/series"
LICENSE_FILE="/media/shared/home/dbi/FileBot_License_PX76319004.psm"
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="/opt/filebot_data/filebot_report_$(date +%Y%m%d).txt"

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

# --- Vérifie la licence --------------------------------------------------------
install_license() {
  if ! filebot --license | grep -q "Valid-Until"; then
    log "🪪 Installation de la licence FileBot..."
    filebot --license "$LICENSE_FILE" || log "⚠️ Impossible d'installer la licence"
  else
    log "✅ Licence déjà installée."
  fi
}

# --- Détecte la langue originale du film via TMDb ------------------------------
get_original_lang() {
  local path="$1"
  filebot -rename "$path" \
    --db TheMovieDB \
    --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 TYPE APPLY_OPT OUTPUT_DIR

  if [[ "$path" == *"/movies/"* ]]; then
    OUTPUT_DIR="$MEDIA_MOVIES"
    TYPE="film"
    DB="TheMovieDB"
    FORMAT="{n} ({y})/{n} ({y}) - {vf}{' ' + vc ?: ''}{' ' + ac ?: ''}{' - ' + group ?: ''}"
  else
    OUTPUT_DIR="$MEDIA_SERIES"
    TYPE="série"
    DB="TheTVDB"
    FORMAT="{n}/Season {s.pad(2)}/{n} - S{s.pad(2)}E{e.pad(2)} - {t} - {vf}{' ' + vc ?: ''}{' ' + ac ?: ''}{' - ' + group ?: ''}"
  fi

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

  case "$original_lang" in
    fr|fre|fra|es|spa|it|ita|nl|dut|nld)
      lang_meta="fr"
      APPLY_OPT="artwork,nfo"
      ;;
    *)
      lang_meta="en"
      [[ "$FORCE_ARTWORK" == "true" ]] && APPLY_OPT="artwork,nfo" || APPLY_OPT="nfo"
      ;;
  esac

  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

  filebot -rename "$path" \
    --db "$DB" \
    --lang "$lang_meta" \
    --action "$ACTION" \
    --conflict override \
    --output "$OUTPUT_DIR" \
    --format "$FORMAT" \
    --apply "$APPLY_OPT" \
    || log "⚠️ Erreur FileBot sur $path"

  # --- Renomme le dossier lui-même -------------------------------------------
  local base_name new_name parent_dir
  base_name=$(basename "$path")
  new_name=$(filebot -rename "$path" \
    --db "$DB" \
    --action test \
    --format "{n} ({y})" 2>/dev/null | grep -v '/')
  parent_dir=$(dirname "$path")

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

  # --- Nettoyage & permissions ------------------------------------------------
  find "$OUTPUT_DIR" -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 (bare-metal /media/movies, /media/series) ==="
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é"
