#!/usr/bin/env python3
# SPDX-License-Identifier: Unlicense

# This script allows you to use the DeArrow YouTube extension in Newsboat. Simply save this file
# under ~/.local/bin/yt_dearrow_rss and preprend `filter:~/.local/bin/yt_dearrow_rss:` to an entry in your `urls` file, e.g.
# filter:~/.local/bin/yt_dearrow_rss:https://www.youtube.com/feeds/videos.xml?channel_id=UCeiYXex_fwgYDonaTcSIk6w MinuteEarth

import requests
import xml.etree.ElementTree as ET
import sys


def fetch_dearrow_title(video_id) -> str | None:
    """Get best non-clickbaity title from DeArrow's community database"""

    # https://wiki.sponsor.ajay.app/w/API_Docs/DeArrow
    r = requests.get(f"https://dearrow.minibomba.pro/sbserver/api/branding/?videoID={video_id}").json()
    if not r["titles"]:
        return None

    best = r["titles"][0]
    if best["locked"] or best["votes"] >= 0:
        return best["title"]
    else:
        return None


tree = ET.parse(sys.stdin)
root = tree.getroot()

namespaces = {
    "yt": "http://www.youtube.com/xml/schemas/2015",
    "media": "http://search.yahoo.com/mrss/",
    "": "http://www.w3.org/2005/Atom",
}

for k, v in namespaces.items():
    ET.register_namespace(k, v)

for entry in root.findall("entry", namespaces):
    if new_title := fetch_dearrow_title(entry.find("yt:videoId", namespaces).text):
        title_element = entry.find("title", namespaces)
        if title_element is not None:
            title_element.text = f"{new_title}  ◎  {title_element.text}"

sys.stdout.buffer.write(ET.tostring(root))
