#!/usr/bin/sh
set -eu

usage() {
  echo "usage: yabo-add <url> [name]" >&2
  exit 64
}

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

[ "$#" -ge 1 ] || usage
url=$1
name=${2:-}
rec="$YA_ROOT/subscriptions.rec"

# Schema-in-code: create the file with the current %allowed if absent, instead
# of a shipped seed the playbook could never migrate.
ensure_subscriptions "$rec"

# Re-adding a channel is a common slip; catch it with a cheap local lookup
# before the ~2s yt-dlp resolution. Exit 3 (distinct from usage/64 and
# runtime/1) so callers can tell "already subscribed" from a real failure.
if [ -n "$(recsel -t Subscription -e "Url = '$url'" -P Url "$rec")" ]; then
  echo "already subscribed: $url" >&2
  exit 3
fi

# Resolve the stable channel id now so the RSS detector can derive each
# channel's UULF uploads-playlist feed without re-scraping every run.
# channel_id is a playlist-level field, so it must be read with the "playlist:"
# print prefix; a plain --print channel_id on a --flat-playlist entry yields NA.
# --playlist-items 0 fetches the channel metadata without extracting any video.
[ -t 2 ] && echo "resolving channel…" >&2   # the yt-dlp lookup has no meter
cid=$(yt-dlp --js-runtimes node --flat-playlist --playlist-items 0 \
  --print "playlist:%(channel_id)s" "$url" 2>/dev/null | head -n1) || true
case $cid in
  UC*) ;;
  *) echo "cannot resolve channel_id for $url (got '${cid:-}')" >&2; exit 1 ;;
esac

# A different URL for a channel we already track (e.g. @h vs @h/videos) resolves
# to the same ChannelId; the exact-Url check above misses it. Catch it here so a
# channel can't be split across two subscriptions and one shared folder.
existing=$(recsel -t Subscription -e "ChannelId = '$cid'" -P Url "$rec" | head -n1)
if [ -n "$existing" ]; then
  echo "already subscribed as $existing (same channel): $url" >&2
  exit 3
fi

set -- -t Subscription -f Url -v "$url" \
       -f Added -v "$(date +%F)" -f Enabled -v yes \
       -f ChannelId -v "$cid"
[ -n "$name" ] && set -- "$@" -f Name -v "$name"

# The dup check above handles re-adds, so a recins failure here is a genuine
# integrity/schema problem — silence its raw error and report plainly.
recins "$@" "$rec" 2>/dev/null || { echo "could not add (invalid record): $url" >&2; exit 1; }
echo "added: $url"

# Populate the ledger now instead of waiting for the next tick; runs the full
# detector (other channels just 304, so it's cheap), best-effort — timer retries.
RSS=${YA_RSS:-/usr/libexec/yabo/yabo-rss}
if [ -x "$RSS" ]; then
  "$RSS" || echo "note: initial detection fetch failed; the timer will retry" >&2
fi
