#!/bin/bash
# yt-secours.sh — Récupère les dernières vidéos d'une chaîne YouTube.
# Méthode principale : YouTube Data API v3 (clé locale .yt-api-key, fonctionne depuis n'importe quelle IP).
# Secours : collecteur distant sur le mutualisé (re-info.fr/yt-collect.php) si l'API échoue.
# Usage : ./yt-secours.sh <URL_ou_ID_de_chaîne>
# Sortie : JSON (id, titre, date) ou message d'erreur. Code de sortie non-0 si échec.
set -uo pipefail

API_KEY_FILE="/home/alan/SITE/CRON/.yt-api-key"
COLLECT_URL="https://re-info.fr/yt-collect.php"
TOKEN_FILE="/home/alan/SITE/CRON/.yt-token"
MAX_RESULTS=20

arg="${1:-}"
if [[ -z "${arg}" ]]; then
  echo '{"status":"error","reason":"usage: yt-secours.sh <URL_ou_ID_de_chaîne>"}'
  exit 2
fi

channel="$(echo "${arg}" | grep -oE 'UC[A-Za-z0-9_-]{15,}' | head -1)"
handle="$(echo "${arg}" | grep -oE '@[A-Za-z0-9_.-]+' | head -1)"
if [[ -z "${channel}" && -z "${handle}" ]]; then
  echo '{"status":"error","reason":"aucun ID de chaine UC... ni handle @... trouve dans l argument"}'
  exit 2
fi

# Méthode 1 : YouTube Data API v3 (playlistItems, 1 unité/appel)
if [[ -r "${API_KEY_FILE}" ]]; then
  api_key="$(cat "${API_KEY_FILE}" | tr -d '[:space:]')"
  if [[ -n "${api_key}" ]]; then
    # Résolution d'un handle (@Nom) en ID de chaîne si besoin
    if [[ -z "${channel}" ]]; then
      ch_resp="$(curl -sL --max-time 15 "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=${handle}&key=${api_key}" 2>/dev/null)"
      channel="$(echo "${ch_resp}" | grep -oE '"id":\s*"UC[A-Za-z0-9_-]{15,}"' | head -1 | grep -oE 'UC[A-Za-z0-9_-]{15,}' || true)"
      if [[ -z "${channel}" ]]; then
        echo '{"status":"error","reason":"handle introuvable via API"}'
        exit 1
      fi
    fi
    # Playlist "Uploads" d'un canal : UU + ID sans les 2 premiers caractères (UC)
    playlist_id="UU${channel:2}"
    resp="$(curl -sL --max-time 25 "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${playlist_id}&maxResults=${MAX_RESULTS}&key=${api_key}" 2>/dev/null)"
    if echo "${resp}" | grep -q '"items"'; then
      {
        echo -n '{"status":"ok","channel":"'"${channel}"'","videos":'
        echo "${resp}" | python3 -c '
import sys, json
data = json.load(sys.stdin)
videos = []
for item in data.get("items", []):
    sn = item.get("snippet", {})
    vid = sn.get("resourceId", {}).get("videoId") or sn.get("videoId") or ""
    title = sn.get("title", "")
    date = (sn.get("publishedAt", "") or "")[:10]
    if vid:
        videos.append({"id": vid, "title": title, "date": date})
print(json.dumps(videos, ensure_ascii=False))
'
        echo '}'
      } | tr -d '\n'
      echo
      exit 0
    fi
  fi
fi

# Méthode 2 : collecteur distant (mutualisé, autre IP) — secours
if [[ ! -r "${TOKEN_FILE}" ]]; then
  echo '{"status":"error","reason":"token introuvable: '${TOKEN_FILE}'"}'
  exit 2
fi
token="$(cat "${TOKEN_FILE}")"

resp="$(curl -sL --max-time 25 "${COLLECT_URL}?channel=${channel}&token=${token}" 2>/dev/null)"

if [[ -z "${resp}" ]]; then
  echo '{"status":"error","reason":"collecteur distant injoignable"}'
  exit 1
fi
echo "${resp}"
if echo "${resp}" | grep -q '"status":"ok"'; then
  exit 0
else
  exit 1
fi
