"""Find PDFs that name a font macOS downloads only after asking (Font8 catalog, PlatformDelivery
macOS-download) and do not appear to embed it. Raw-byte scan: font dicts inside compressed object
streams are NOT seen (counted as objstm files). Read-only. 2026-11-08, Lab 04 font-dialog reproducer."""
import os, re, sys, plistlib, collections
root, out = sys.argv[1], sys.argv[2]
cat = plistlib.load(open("/System/Library/AssetsV2/com_apple_MobileAsset_Font8/com_apple_MobileAsset_Font8.xml", "rb"))
want = {}
for a in cat["Assets"]:
    for fi in a.get("FontInfo4", []):
        if "macOS-download" in fi.get("PlatformDelivery", []):
            for n in (fi.get("PostScriptFontName", ""), fi.get("FontFamilyName", "").replace(" ", "")):
                if n and not n.startswith("."):
                    want[n.encode()] = fi.get("PostScriptFontName", "")
name_re = re.compile(rb"/BaseFont\s*/([A-Za-z0-9#+\-_.,]+)")
hits, n_files, n_objstm = [], 0, 0
counts = collections.Counter()
for dp, dn, fn in os.walk(root):
    for f in fn:
        if not f.lower().endswith(".pdf"):
            continue
        p = os.path.join(dp, f); n_files += 1
        try:
            b = open(p, "rb").read()
        except OSError:
            continue
        if b"/ObjStm" in b:
            n_objstm += 1
        found = set()
        for m in name_re.finditer(b):
            nm = m.group(1)
            if b"+" in nm[:7]:          # ABCDEF+Name = embedded subset
                continue
            for cand in (nm, nm.split(b",")[0], nm.split(b"-")[0]):
                if cand in want:
                    found.add(want[cand]); break
        if found:
            hits.append((p, ",".join(sorted(found)), b.count(b"/FontFile")))
            counts.update(found)
        if n_files % 10000 == 0:
            print(f"{n_files} files, {len(hits)} hits", flush=True)
with open(out, "w") as fh:
    fh.write("path\tfonts\tfontfile_count\n")
    for h in hits:
        fh.write(f"{h[0]}\t{h[1]}\t{h[2]}\n")
print(f"done: {n_files} PDFs, {n_objstm} with object streams (not fully scanned), {len(hits)} files name a macOS-download font")
for k, v in counts.most_common(30):
    print(f"  {v:6d}  {k}")
