#!/usr/bin/env python3
"""Hacker News daily digest by email. Standard library only. MIT licence.
Emails you yesterday's Hacker News stories that match your keywords or pass a points threshold.
Settings come from environment variables (see the guide at tasktoagent.com/guides/hacker-news-daily-digest-email/)."""
import os, re, sys, json, time, html, smtplib, ssl, urllib.parse, urllib.request
from email.message import EmailMessage

KEYWORDS = [k.strip().lower() for k in os.getenv("HN_KEYWORDS", "").split(",") if k.strip()]
MIN_POINTS = int(os.getenv("HN_MIN_POINTS", "100"))       # stories with this many points are always included
KW_MIN_POINTS = int(os.getenv("HN_KW_MIN_POINTS", "5"))   # keyword matches need at least this many points
HOURS = int(os.getenv("HN_HOURS", "24"))
MAX_ITEMS = int(os.getenv("HN_MAX_ITEMS", "30"))
SEEN_FILE = os.getenv("HN_SEEN_FILE", os.path.expanduser("~/.hn_digest_seen.json"))
API = os.getenv("HN_API", "https://hn.algolia.com/api/v1/search_by_date")

def fetch(since):
    hits, page = [], 0
    while page < 10:
        q = urllib.parse.urlencode({"tags": "story", "numericFilters": f"created_at_i>{since},points>={min(MIN_POINTS, KW_MIN_POINTS)}",
                                    "hitsPerPage": 1000, "page": page})
        req = urllib.request.Request(f"{API}?{q}", headers={"User-Agent": "hn-digest/1.0 (+tasktoagent.com)"})
        for attempt in range(3):
            try:
                with urllib.request.urlopen(req, timeout=20) as r:
                    data = json.load(r); break
            except Exception as e:
                if attempt == 2: raise SystemExit(f"Hacker News API failed: {e}")
                time.sleep(5 * (attempt + 1))
        hits += data.get("hits", [])
        page += 1
        if page >= data.get("nbPages", 0): break
    return hits

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

def pick(hits, seen):
    out = []
    for h in hits:
        if h["objectID"] in seen: continue
        kw = matches(h); pts = h.get("points") or 0
        if pts >= MIN_POINTS or (kw and pts >= KW_MIN_POINTS):
            h["_kw"] = kw; out.append(h)
    out.sort(key=lambda h: (not h["_kw"], -(h.get("points") or 0)))
    return out[:MAX_ITEMS]

def render(items):
    txt, rows = [], []
    for h in items:
        link = h.get("url") or f"https://news.ycombinator.com/item?id={h['objectID']}"
        disc = f"https://news.ycombinator.com/item?id={h['objectID']}"
        tag = f" [{', '.join(h['_kw'])}]" if h["_kw"] else ""
        meta = f"{h.get('points',0)} points, {h.get('num_comments') or 0} comments"
        txt.append(f"- {h['title']}{tag}\n  {link}\n  {meta}: {disc}")
        rows.append(f'<li><a href="{html.escape(link)}">{html.escape(h["title"])}</a>{html.escape(tag)}<br>'
                    f'<small>{meta} · <a href="{disc}">discussion</a></small></li>')
    return "\n".join(txt), "<ol>" + "".join(rows) + "</ol>"

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
    seen = {}
    if os.path.exists(SEEN_FILE):
        seen = json.load(open(SEEN_FILE))
    cutoff = time.time() - 7 * 86400
    seen = {k: v for k, v in seen.items() if v > cutoff}
    items = pick(fetch(int(time.time()) - HOURS * 3600), seen)
    if not items:
        print("Nothing new today; no email sent."); return
    txt, htm = render(items)
    subject = f"Hacker News digest: {len(items)} stories" + (f" ({sum(1 for h in items if h['_kw'])} match your keywords)" if KEYWORDS else "")
    if dry:
        print(subject + "\n\n" + txt)
    else:
        send(subject, txt, htm); print("Sent:", subject)
    for h in items: seen[h["objectID"]] = time.time()
    if not dry:
        json.dump(seen, open(SEEN_FILE, "w"))

if __name__ == "__main__":
    main()
