#!/usr/bin/env python3
"""Post new RSS or Atom feed items to social media with the Ampost API.

Run it from cron (or a scheduled GitHub Actions job). Each run reads the feed,
posts every item it has not seen before, and remembers the items in a small
JSON state file. The first run only records the current items, so an existing
feed doesn't flood your accounts; pass --post-existing to post them too.
Python 3.8+, standard library only.

    export AMPOST_API_KEY=amp_live_...
    python rss_to_social.py --feed https://example.com/feed.xml --platforms bluesky,threads
    # crontab: every 30 minutes
    */30 * * * * cd /opt/rss && AMPOST_API_KEY=amp_live_... python3 rss_to_social.py \
        --feed https://example.com/feed.xml --platforms bluesky,threads

Guide: https://ampost.io/how-to/rss-feed-to-social-media
"""

import argparse
import hashlib
import json
import os
import sys
import urllib.error
import urllib.request
import xml.etree.ElementTree as ElementTree

API_URL = os.environ.get("AMPOST_API_URL", "https://api.ampost.io").rstrip("/")
ATOM = "{http://www.w3.org/2005/Atom}"
# Items read per run, newest first. Older items beyond this are never posted.
MAX_ITEMS = 20
# Seen item ids kept in the state file.
MAX_SEEN = 500


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "ampost-rss-template/1.0"})
    with urllib.request.urlopen(request, timeout=30) as response:
        return response.read()


def parse_feed(xml_bytes):
    """Return [{id, title, link}] for an RSS 2.0 or Atom feed, in feed order (newest first)."""
    root = ElementTree.fromstring(xml_bytes)
    items = []
    for item in root.iter("item"):  # RSS 2.0
        link = (item.findtext("link") or "").strip()
        guid = (item.findtext("guid") or "").strip()
        items.append({"id": guid or link, "title": (item.findtext("title") or "").strip(), "link": link})
    for entry in root.iter(ATOM + "entry"):  # Atom
        link = ""
        for element in entry.findall(ATOM + "link"):
            if element.get("rel", "alternate") == "alternate":
                link = element.get("href", "")
                break
        entry_id = (entry.findtext(ATOM + "id") or "").strip()
        items.append({"id": entry_id or link, "title": (entry.findtext(ATOM + "title") or "").strip(), "link": link})
    return [item for item in items if item["id"]][:MAX_ITEMS]


def item_key(feed_url, item):
    """A stable Idempotency-Key per feed item: a re-run never posts the same item twice."""
    return "rss-" + hashlib.sha256((feed_url + "\n" + item["id"]).encode("utf-8")).hexdigest()[:40]


def post_item(api_key, platforms, item, feed_url, template):
    body = {
        "targets": [{"platforms": platforms}],
        "text": template.format(title=item["title"], link=item["link"]).strip(),
        "publishNow": True,
    }
    if item["link"].startswith("https://") or item["link"].startswith("http://"):
        body["linkUrl"] = item["link"]
    request = urllib.request.Request(
        API_URL + "/api/posts",
        data=json.dumps(body).encode("utf-8"),
        method="POST",
        headers={
            "Authorization": "Bearer " + api_key,
            "Content-Type": "application/json",
            "Idempotency-Key": item_key(feed_url, item),
            "User-Agent": "ampost-rss-template/1.0",
        },
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        return json.loads(response.read().decode("utf-8"))


def load_state(path):
    try:
        with open(path, encoding="utf-8") as handle:
            return json.load(handle)
    except FileNotFoundError:
        return None


def save_state(path, seen):
    temp = path + ".tmp"
    with open(temp, "w", encoding="utf-8") as handle:
        json.dump({"seen": seen[-MAX_SEEN:]}, handle, indent=2)
    os.replace(temp, path)


def main(argv=None):
    parser = argparse.ArgumentParser(description="Post new RSS/Atom items to social media with Ampost.")
    parser.add_argument("--feed", required=True, help="the RSS or Atom feed URL")
    parser.add_argument("--platforms", required=True, help="comma-separated, e.g. bluesky,threads,discord")
    parser.add_argument("--template", default="{title}", help='post text; {title} and {link} are filled in (default "{title}")')
    parser.add_argument("--state", default="rss_state.json", help="where seen items are remembered")
    parser.add_argument("--post-existing", action="store_true", help="on the first run, post the items already in the feed")
    args = parser.parse_args(argv)

    api_key = os.environ.get("AMPOST_API_KEY")
    if not api_key:
        raise SystemExit("Set AMPOST_API_KEY to an API key from https://ampost.io/app/settings/api-keys")
    platforms = [p.strip() for p in args.platforms.split(",") if p.strip()]

    items = parse_feed(fetch(args.feed))
    state = load_state(args.state)
    if state is None and not args.post_existing:
        save_state(args.state, [item["id"] for item in reversed(items)])
        print("First run: remembered %d existing items, posted none." % len(items))
        return 0

    seen = list(state["seen"]) if state else []
    failed = 0
    for item in reversed(items):  # oldest new item first
        if item["id"] in seen:
            continue
        try:
            post = post_item(api_key, platforms, item, args.feed, args.template)
        except urllib.error.HTTPError as error:
            payload = error.read().decode("utf-8", "replace")
            if error.code == 409 and "IDEMPOTENCY_KEY_REUSED" in payload:
                # Posted within the last 24 hours with other settings (template, platforms).
                print("Already posted: %s" % item["title"])
            else:
                failed += 1
                print("Not posted (%s): %s %s" % (error.code, item["title"], payload[:300]), file=sys.stderr)
                if error.code == 429 or error.code >= 500:
                    continue  # try again on the next run
                # Other 4xx: Ampost refused the item (for example too long for a platform); don't retry it forever.
        except urllib.error.URLError as error:
            failed += 1
            print("Could not reach %s: %s" % (API_URL, error.reason), file=sys.stderr)
            continue  # try again on the next run
        else:
            print("Posted %s (%s): %s" % (post["id"], post["status"], item["title"]))
        seen.append(item["id"])
        save_state(args.state, seen)
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
