#!/usr/bin/env python3
"""Find a site's feed the way the probe found them: autodiscovery on the front page,
then three guessed paths, then the hand list of big sites that hide theirs (hidden.csv,
every row checked on the date it carries). Standard library plus `requests`.

Usage: python find_feed.py example.com [another.org ...]
Prints one line per feed found: domain, how it was found, format, item count, newest item, URL.
Exit status 0 when every domain yielded at least one feed, 1 otherwise.
"""
import csv, os, sys
from urllib.parse import urljoin, urlparse
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import probe

HERE = os.path.dirname(os.path.abspath(__file__))


def hand_list():
    p = os.path.join(HERE, "hidden.csv")
    if not os.path.exists(p):
        return {}
    out = {}
    for row in csv.DictReader(open(p)):
        out.setdefault(row["domain"], []).append(row["feed_url"])
    return out


def bare(domain):
    d = domain.strip().lower()
    if "//" in d:
        d = urlparse(d).netloc
    return d[4:] if d.startswith("www.") else d


def find(domain):
    d = bare(domain)
    found = []
    status, ctype, body, final, err = probe.get(f"https://{d}/")
    if not err and status == 200:
        html = body.decode("utf-8", "replace")
        for f in probe.advertised(html, final)[:5]:
            c = probe.check_feed(f["url"])
            if c["kind"] != "none":
                found.append(("advertised", c))
    if not found:
        base = final if (not err and status == 200) else f"https://{d}/"
        for path in probe.GUESSES:
            c = probe.check_feed(urljoin(base, path))
            if c["kind"] != "none":
                found.append(("guessed", c))
    if not found:
        for url in hand_list().get(d, []):
            c = probe.check_feed(url)
            if c["kind"] != "none":
                found.append(("hand list", c))
    return d, found


def main(argv):
    if not argv:
        print(__doc__); return 2
    missing = 0
    for domain in argv:
        d, found = find(domain)
        if not found:
            missing += 1
            print(f"{d}\tnone found (autodiscovery, /feed, /rss.xml, /atom.xml, hand list)")
        for how, c in found:
            print(f"{d}\t{how}\t{c['kind']}\t{c['items']}\t{(c['newest'] or '')[:10]}\t{c['url']}")
    return 1 if missing else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
