#!/usr/bin/sh
set -eu

CONFIG=${YA_CONFIG:-/etc/yabo/config}
# shellcheck source=/dev/null
. "$CONFIG"
LIB=${YA_LIB:-/usr/share/yabo/lib.sh}
# shellcheck source=/dev/null
. "$LIB"

REC="$YA_ROOT/subscriptions.rec"
GEN=${YA_GEN:-/usr/share/yabo/gen.php}
SB=${YA_SB:-/usr/share/yabo/sb.php}
SB_API="https://sponsor.ajay.app"
# Fixed, pre-URL-encoded fetch spec — the category mapping is the allow-list.
# categories=["sponsor","selfpromo","interaction","music_offtopic","intro",
#   "outro","preview","poi_highlight"] & actionTypes=["skip","poi"]
SB_QUERY='categories=%5B%22sponsor%22%2C%22selfpromo%22%2C%22interaction%22%2C%22music_offtopic%22%2C%22intro%22%2C%22outro%22%2C%22preview%22%2C%22poi_highlight%22%5D&actionTypes=%5B%22skip%22%2C%22poi%22%5D'
ETAGS="$YA_CACHE_DIR/sb-etags"; mkdir -p "$ETAGS"

# recsel selection expression for a named tier; empty => caller passed --select.
tier_sex() {
  case $1 in
    fast) printf "Downloaded != '' && Downloaded >> '1 day ago'" ;;
    mid)  printf "Downloaded != '' && Downloaded << '1 day ago' && Downloaded >> '3 days ago'" ;;
    slow) printf "Downloaded != '' && Downloaded << '3 days ago'" ;;
    *) return 1 ;;
  esac
}

# Media file for an id present in dir? (quoted [id] in case = literal match)
media_present() {
  d=$1; i=$2
  for f in "$d"/*; do
    [ -e "$f" ] || continue
    case $f in
      *"[$i]".nfo|*"[$i]".info.json|*"[$i]".jpg|*"[$i]".jpeg|*"[$i]".png|*"[$i]".webp|*"[$i]".edl|*"[$i]".chapters.json) continue ;;
      *"[$i]".*) return 0 ;;
    esac
  done
  return 1
}
has_edl() { for f in "$1"/*; do case $f in *"[$2]".edl) return 0 ;; esac; done; return 1; }
info_for() { for f in "$1"/*; do case $f in *"[$2]".info.json) printf '%s' "$f"; return 0 ;; esac; done; return 1; }

[ "$#" -ge 1 ] || { echo "usage: yabo-sb fast|mid|slow | --select '<SEX>'" >&2; exit 64; }
MODE=$1; SEX=""; SKIP_WITH_EDL=0
case $MODE in
  --select) [ "$#" -ge 2 ] || { echo "usage: yabo-sb --select '<SEX>'" >&2; exit 64; }
            SEX=$2 ;;
  fast|mid) SEX=$(tier_sex "$MODE") ;;
  slow)     SEX=$(tier_sex slow); SKIP_WITH_EDL=1 ;;
  *) echo "usage: yabo-sb fast|mid|slow | --select '<SEX>'" >&2; exit 64 ;;
esac

FEEDS=$(mktemp); MAP=$(mktemp); TOUCHED=$(mktemp); BODIES=$(mktemp -d)
trap 'rm -rf "$FEEDS" "$MAP" "$TOUCHED" "$BODIES"' EXIT
{ echo 'parallel'; echo 'http2'; [ -t 2 ] || echo 'no-progress-meter'; } > "$FEEDS"

# Build one curl -K batch across every due video of every enabled channel.
recsel -t Subscription -C -e "#Enabled = 0 || Enabled = 'yes'" -P Url "$REC" \
| while IFS= read -r url; do
    [ -n "$url" ] || continue
    dir="$YA_ROOT/$(sanitize "$url")"
    cr="$dir/Channel.rec"; [ -e "$cr" ] || continue
    recsel -t Video -C -e "$SEX" -P Id "$cr" \
    | while IFS= read -r id; do
        [ -n "$id" ] || continue
        media_present "$dir" "$id" || continue          # skip deleted tombstones
        [ "$SKIP_WITH_EDL" -eq 1 ] && has_edl "$dir" "$id" && continue
        et="$ETAGS/$id"; [ -f "$et" ] || : > "$et"
        printf '%s\t%s\n' "$id" "$dir" >> "$MAP"
        {
          echo '--next'
          echo 'url = "'"$SB_API"'/api/skipSegments?videoID='"$id"'&'"$SB_QUERY"'"'
          printf 'write-out = "%%{http_code} %%{url}\\n"\n'
          echo 'etag-compare = "'"$et"'"'
          echo 'etag-save = "'"$et"'"'
          echo 'output = "'"$BODIES/$id.json"'"'
        } >> "$FEEDS"
      done
  done

grep -q '^url = ' "$FEEDS" || exit 0
# A --next batch keeps going past a failed transfer but still exits nonzero;
# || true stops one bad transport blip from aborting the whole tier's run.
SUMMARY=$(curl -K "$FEEDS") || true

printf '%s\n' "$SUMMARY" | while IFS=' ' read -r code url; do
  id=$(printf '%s' "$url" | sed -n 's/.*videoID=\([^&]*\).*/\1/p')
  [ -n "$id" ] || continue
  dir=$(awk -F '\t' -v k="$id" '$1 == k {print $2; exit}' "$MAP")
  [ -n "$dir" ] || continue
  body="$BODIES/$id.json"
  case $code in
    200)
      info=$(info_for "$dir" "$id") || continue
      base=${info%.info.json}
      php "$SB" "$body" "$info" "$base.edl" "$base.chapters.json" \
        || echo "warn: sb.php failed for $id" >&2
      printf '%s\n' "$dir" >> "$TOUCHED"
      ;;
    *) : ;;   # 304 unchanged / 404 no segments / other -> nothing
  esac
  rm -f "$body"
done

# Regenerate the feed once per touched channel (idempotent, atomic).
sort -u "$TOUCHED" | while IFS= read -r dir; do
  [ -n "$dir" ] || continue
  php "$GEN" feed "$dir" "$YA_BASE_URL" || echo "warn: feed regen $dir" >&2
done
