#!/usr/bin/env python3
"""RSS to email daily digest. Standard library only. MIT licence.
Reads several RSS or Atom feeds, keeps new items (optionally only those matching your keywords)
and emails them to you as one message with a plain-text and an HTML part.
Settings come from environment variables (see tasktoagent.com/guides/rss-to-email-daily-digest/)."""
import os, re, sys, json, time, html, smtplib, ssl, urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from email.message import EmailMessage
from email.utils import parsedate_to_datetime

FEEDS = [f.strip() for f in os.getenv("RSS_FEEDS", "").split(",") if f.strip()]
KEYWORDS = [k.strip().lower() for k in os.getenv("RSS_KEYWORDS", "").split(",") if k.strip()]
MAX_AGE_HOURS = int(os.getenv("RSS_MAX_AGE_HOURS", "48"))   # skip items older than this (0 = no limit)
MAX_ITEMS = int(os.getenv("RSS_MAX_ITEMS", "50"))           # per email, all feeds together
SEEN_FILE = os.getenv("RSS_SEEN_FILE", os.path.expanduser("~/.rss_digest_seen.json"))
SEEN_DAYS = 30                                               # how long sent ids are remembered

def local(tag):  # "{http://www.w3.org/2005/Atom}entry" -> "entry"
    return tag.rsplit("}", 1)[-1]

def child(el, *names):
    for c in el:
        if local(c.tag) in names:
            return c
    return None

def text(el, *names):
    c = child(el, *names)
    return (c.text or "").strip() if c is not None and c.text else ""

def when(s):
    if not s: return None
    try:
        d = parsedate_to_datetime(s)            # RSS: "Thu, 22 Oct 2026 19:05:00 +0000"
    except (TypeError, ValueError):
        try: d = datetime.fromisoformat(s.replace("Z", "+00:00"))   # Atom: "2026-10-22T19:05:00Z"
        except ValueError: return None
    return d if d.tzinfo else d.replace(tzinfo=timezone.utc)

def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": "rss-digest/1.0 (+tasktoagent.com)"})
    with urllib.request.urlopen(req, timeout=20) as r:
        root = ET.fromstring(r.read())
    if local(root.tag) not in ("rss", "feed", "RDF"):
        raise ValueError(f"not an RSS or Atom feed (the page starts with <{local(root.tag)}>)")
    feed_title = text(child(root, "channel") if child(root, "channel") is not None else root, "title") or url
    items = []
    for el in root.iter():
        if local(el.tag) not in ("item", "entry"): continue
        link = text(el, "link")
        if not link:  # Atom: <link rel="alternate" href="..."/>
            for c in el:
                if local(c.tag) == "link" and c.get("rel", "alternate") == "alternate" and c.get("href"):
                    link = c.get("href"); break
        title = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", text(el, "title")))) or link or "(no title)"
        summary = text(el, "description", "summary", "content")
        summary = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", summary))).strip()
        uid = text(el, "guid", "id") or link or title
        items.append({"id": url + "|" + uid, "title": title, "link": link, "summary": summary[:200],
                      "date": when(text(el, "pubDate", "published", "updated", "date")), "feed": feed_title})
    return feed_title, items

def matches(it):
    if not KEYWORDS: return True
    t = (it["title"] + " " + it["summary"]).lower()
    # whole words only, so "ai" doesn't match "email" and "go" doesn't match "google"
    return any(re.search(r"(?<![a-z0-9])" + re.escape(k) + r"(?![a-z0-9])", t) for k in KEYWORDS)

def render(items):
    txt, htm, last = [], [], None
    for it in items:
        if it["feed"] != last:
            txt.append(f"\n== {it['feed']} =="); htm.append(f"<h3>{html.escape(it['feed'])}</h3>")
            last = it["feed"]
        txt.append(f"- {it['title']}\n  {it['link']}")
        htm.append(f'<p><a href="{html.escape(it["link"])}">{html.escape(it["title"])}</a>'
                   + (f"<br><small>{html.escape(it['summary'])}</small>" if it["summary"] else "") + "</p>")
    return "\n".join(txt).strip(), "".join(htm)

def send(subject, txt, htm):
    msg = EmailMessage()
    msg["Subject"], msg["From"], msg["To"] = subject, os.environ["SMTP_FROM"], os.environ["SMTP_TO"]
    msg.set_content(txt); msg.add_alternative(f"<html><body>{htm}</body></html>", subtype="html")
    host, port = os.environ["SMTP_HOST"], int(os.getenv("SMTP_PORT", "465"))
    user, pw = os.getenv("SMTP_USER"), os.getenv("SMTP_PASSWORD")
    if port == 465:
        s = smtplib.SMTP_SSL(host, port, context=ssl.create_default_context(), timeout=30)
    else:
        s = smtplib.SMTP(host, port, timeout=30)
        if os.getenv("SMTP_STARTTLS", "1") == "1": s.starttls(context=ssl.create_default_context())
    with s:
        if user: s.login(user, pw)
        s.send_message(msg)

def main():
    dry = "--dry-run" in sys.argv
    if not FEEDS: raise SystemExit("Set RSS_FEEDS to one or more feed URLs, separated by commas.")
    seen = json.load(open(SEEN_FILE)) if os.path.exists(SEEN_FILE) else {}
    seen = {k: v for k, v in seen.items() if v > time.time() - SEEN_DAYS * 86400}
    now, new, failed = datetime.now(timezone.utc), [], []
    for url in FEEDS:
        try:
            name, items = fetch(url)
        except Exception as e:  # one broken feed must not stop the others
            print(f"Skipped {url}: {e}", file=sys.stderr); failed.append(url); continue
        fresh = [it for it in items if it["id"] not in seen and matches(it)
                 and not (MAX_AGE_HOURS and it["date"] and (now - it["date"]).total_seconds() > MAX_AGE_HOURS * 3600)]
        print(f"{name}: {len(items)} items, {len(fresh)} new", file=sys.stderr)
        new += fresh
    if len(failed) == len(FEEDS): raise SystemExit("All feeds failed; no email sent.")
    new = new[:MAX_ITEMS]
    if not new:
        print("Nothing new; no email sent."); return
    txt, htm = render(new)
    if failed:
        txt += "\n\nCould not read: " + ", ".join(failed)
        htm += "<p><small>Could not read: " + html.escape(", ".join(failed)) + "</small></p>"
    subject = f"RSS digest: {len(new)} new item{'s' if len(new) != 1 else ''} from {len({i['feed'] for i in new})} feed(s)"
    if dry:
        print(subject + "\n\n" + txt); return
    send(subject, txt, htm); print("Sent:", subject)
    for it in new: seen[it["id"]] = time.time()
    json.dump(seen, open(SEEN_FILE, "w"))

if __name__ == "__main__":
    main()
