"""Second pass for sites marked without a favicon: retries every <link rel=icon> href
(not only the first) and /favicon.ico once, to rule out a timeout on the first pass."""
import json
from urllib.parse import urljoin, urlsplit
from measure import fetch
rows = [json.loads(l) for l in open("results.jsonl")]
def is_icon(f):
    b = f["body"]
    return f["code"] == 200 and len(b) > 0 and ("image" in f["ctype"] or "icon" in f["ctype"]
            or b[:4] in (b"\x00\x00\x01\x00", b"\x89PNG") or b"<svg" in b[:500])
for r in rows:
    if not r.get("serving") or r["favicon_ok"]:
        continue
    p = urlsplit(r["home_final"])
    urls = [urljoin(r["home_final"], h) for h in r["icon_links"] if not h.startswith("data:")]
    urls.append(f"{p.scheme}://{p.netloc}/favicon.ico")
    for u in dict.fromkeys(urls):
        if is_icon(fetch(u, max_bytes=2_000_000)):
            r["favicon_ok"] = True; r["favicon_src"] = u + " (second pass)"; break
    print(r["domain"], r["favicon_ok"])
with open("results.jsonl", "w") as f:
    for r in rows: f.write(json.dumps(r) + "\n")
