#!/bin/bash

trap 'echo "❌ Erreur à la ligne $LINENO. Code: $?."' ERR
# set -euo pipefail

# 📡 Configuration qBittorrent
QBT_URL="http://localhost:8080"
QBT_USER="admin"
QBT_PASS="Vocalize_Void_Rage_Visor_Ladies_Undercook_Spokesman_Fraternal"

# 📁 Liste des trackers privés depuis fichier
PRIVATE_TRACKERS=()
TRACKERS_FILE="$(dirname "$0")/private_trackers.txt"
if [[ -f "$TRACKERS_FILE" ]]; then
  mapfile -t PRIVATE_TRACKERS < <(grep -vE '^\s*#|^\s*$' "$TRACKERS_FILE" | tr -d '\r' | sed 's/ *$//' | tr '[:upper:]' '[:lower:]')
else
  echo "❌ Fichier de trackers privés introuvable : $TRACKERS_FILE"
  exit 1
fi

# ⚙️ Options
DRY_RUN=false
LOG_FILE=""
FORCE=false
FILTER_LABEL=""
FILTER_LABEL_EXCLUDE_PRIVATE=""
COOKIE_FILE="/tmp/qbt_cookie.txt"
CSV_REPORT="qbt_tracker_report.csv"

# 🔢 Compteurs
total=0
private_count=0
public_count=0
skipped_count=0
label_added=0

# 🕹️ Parsing arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) DRY_RUN=true ;;
    --log) shift; LOG_FILE="$1" ;;
    --force) FORCE=true ;;
    --filter-label) shift; FILTER_LABEL="$1" ;;
    --filter-label-exclude-private) shift; FILTER_LABEL_EXCLUDE_PRIVATE="$1" ;;
    *) echo "❌ Unknown option: $1"; exit 1 ;;
  esac
  shift
done

log() {
  echo "$1"
  [[ -n "${LOG_FILE:-}" ]] && echo "$(date +'%F %T') | $1" >> "$LOG_FILE"
}

login() {
  curl -sf -c "$COOKIE_FILE" --data "username=$QBT_USER&password=$QBT_PASS" "$QBT_URL/api/v2/auth/login" | grep -q "Ok." || {
    log "❌ Login failed"
    exit 1
  }
  log "✅ Connexion réussie à qBittorrent"
}

get_torrents() {
  curl -sf -b "$COOKIE_FILE" "$QBT_URL/api/v2/torrents/info"
}

get_main_tracker() {
  local hash="$1"
  curl -sf -b "$COOKIE_FILE" "$QBT_URL/api/v2/torrents/trackers?hash=$hash" \
    | jq -r '.[] | select(.url | test("^https?://")) | .url' | head -n 1
}

set_ratio() {
  local hash="$1"
  local ratio="$2"
  if $DRY_RUN; then
    log "🧪 [Dry-run] Would set ratio=$ratio on $hash"
  else
    curl -sf -b "$COOKIE_FILE" --data "hashes=$hash&ratioLimit=$ratio&seedingTimeLimit=-1" "$QBT_URL/api/v2/torrents/setShareLimits"
  fi
}

set_label() {
  local hash="$1"
  if $DRY_RUN; then
    log "🏷️ [Dry-run] Would set label 'ygg' on $hash"
  else
    curl -sf -b "$COOKIE_FILE" --data "hashes=$hash&label=ygg" "$QBT_URL/api/v2/torrents/setLabel"
  fi
}

main() {
  login

  if [[ -n "$FILTER_LABEL" ]]; then
    log "🔎 Filtrage des torrents avec label : '$FILTER_LABEL'"
    mapfile -t torrents < <(get_torrents | jq -rc --arg flabel "$FILTER_LABEL" '.[] | select(has("tags") and (.tags | split(",") | index($flabel))) | [.hash, .name] | @tsv')

  elif [[ -n "$FILTER_LABEL_EXCLUDE_PRIVATE" ]]; then
    log "🔎 Filtrage des torrents avec label '$FILTER_LABEL_EXCLUDE_PRIVATE' EXCLUANT les trackers privés"
    mapfile -t torrents < <(get_torrents | jq -rc --arg flabel "$FILTER_LABEL_EXCLUDE_PRIVATE" '.[] | select(has("tags") and (.tags | split(",") | index($flabel))) | [.hash, .name] | @tsv')

  else
    echo "name,hash,tracker,current_ratio" > "$CSV_REPORT"
    mapfile -t torrents < <(get_torrents | jq -rc '.[] | [.hash, .name] | @tsv')
  fi

  log "📦 Nombre de torrents détectés : ${#torrents[@]}"

  for t in "${torrents[@]}"; do
    [[ "$t" == *$'\t'* ]] || { log "⚠️ Ligne malformée: $t" ; ((skipped_count++)); continue; }
    IFS=$'\t' read -r hash name <<< "$t"

    log "➡️ Traitement du torrent : ${name:-<inconnu>} (${hash:-<inconnu>})"
    ((total++))

    tracker=$(get_main_tracker "$hash" || echo "")
    tracker=$(echo "$tracker" | tr '[:upper:]' '[:lower:]')
    current_ratio=$(curl -sf -b "$COOKIE_FILE" "$QBT_URL/api/v2/torrents/properties?hash=$hash" | jq -r '.max_ratio')

    if [[ -n "$FILTER_LABEL" ]]; then
      echo -e "\n🎯 ${name}\n   Tracker : ${tracker}\n   Ratio   : ${current_ratio}"
      continue
    fi

    if [[ -n "$FILTER_LABEL_EXCLUDE_PRIVATE" ]]; then

      # Tracker vide ou non-HTTP → on ignore
      if [[ -z "$tracker" || "$tracker" != http* ]]; then
        log "❌ Tracker invalide ou absent → $name"
        continue
      fi

      # Normalisation
      tracker_lc=$(echo "$tracker" | tr '[:upper:]' '[:lower:]')

      # Recherche partielle dans l’URL du tracker
      for pattern in "${PRIVATE_TRACKERS[@]}"; do
        if [[ "$tracker_lc" == *"$pattern"* ]]; then
          log "❌ Tracker privé détecté → $name ($tracker)"
          continue 2  # saute à la prochaine boucle du `for t in ...`
        fi
      done

      # Tracker non privé → afficher
      echo -e "\n🎯 ${name}\n   Tracker : ${tracker}\n   Ratio   : ${current_ratio}"
      continue
    fi

    echo "\"${name}\",${hash},\"${tracker}\",${current_ratio}" >> "$CSV_REPORT"

    ratio=2.0
    for pattern in "${PRIVATE_TRACKERS[@]}"; do
      if [[ "$tracker" == *"$pattern"* ]]; then
        ratio=-1
        ((private_count++))
        set_label "$hash"
        ((label_added++))
        break
      fi
    done

    [[ $ratio == 2.0 ]] && ((public_count++))

    if ! $FORCE && [[ "$current_ratio" == "$ratio" ]]; then
      log "↪️  Ratio déjà défini pour $name (=$current_ratio), rien à faire"
      continue
    fi

    set_ratio "$hash" "$ratio"
  done

  rm -f "$COOKIE_FILE"

  [[ -z "$FILTER_LABEL" && -z "$FILTER_LABEL_EXCLUDE_PRIVATE" ]] && {
    echo
    log "📊 Résumé :"
    log "  Total analysés     : $total"
    log "  Torrents privés    : $private_count"
    log "  Label 'ygg' ajoutés: $label_added"
    log "  Torrents publics   : $public_count"
    log "  Trackers inconnus  : $skipped_count"
    log "📄 CSV généré : $CSV_REPORT"
  }
}

main