"""Second pass for sitemaps: the first pass accepted only XML (<urlset> or <sitemapindex>), but Google also
accepts a plain text sitemap with one URL per line. This refetches the first sitemap listed in robots.txt
(or /sitemap.xml) for every serving site whose sitemap failed, and accepts a 200 text file whose first
non-empty lines are absolute http(s) URLs. Rewrites sitemap_ok and sitemap_listed_but_broken in results.jsonl."""
import gzip, json
from urllib.parse import urljoin, urlsplit
from measure import fetch, is_sitemap
rows = [json.loads(l) for l in open("results.jsonl")]


def is_text_sitemap(res):
    if res["code"] != 200:
        return False
    b = res["body"]
    if b[:2] == b"\x1f\x8b":
        try:
            b = gzip.decompress(b)
        except Exception:
            return False
    lines = [l.strip() for l in b[:20000].decode("utf-8", "replace").splitlines() if l.strip()][:5]
    return bool(lines) and all(l.startswith(("http://", "https://")) and " " not in l for l in lines)


for r in rows:
    if not r.get("serving") or r["sitemap_ok"]:
        continue
    p = urlsplit(r["home_final"])
    origin = f"{p.scheme}://{p.netloc}"
    for u in (r["robots_sitemaps"][:1] or [origin + "/sitemap.xml"]):
        res = fetch(urljoin(origin + "/", u), max_bytes=20_000_000)
        if is_sitemap(res) or is_text_sitemap(res):
            r["sitemap_ok"] = True; r["sitemap_url"] = u + " (second pass)"
    r["sitemap_listed_but_broken"] = r["sitemap_in_robots"] and not r["sitemap_ok"]
    print(r["domain"], r["sitemap_ok"])
with open("results.jsonl", "w") as f:
    for row in rows:
        f.write(json.dumps(row) + "\n")
