#!/usr/bin/env python3
"""
Independently reproduce the three headline figures of the lostinconsoles.com audit.

The point of this script is that it does NOT trust the author. It fetches the
sitemap from a source the author cannot edit -- the Internet Archive capture made
before the audit was published -- recomputes the path-segment distribution, and
fails loudly if anything does not reconcile.

Run it yourself:

    python3 reproduce.py

Exit 0 = the audit reproduces. Exit 1 = it does not, and the mismatch is printed.

No dependencies beyond the Python standard library.
"""
import hashlib
import re
import sys
import urllib.request

# The archived copy. This URL was captured by the Internet Archive, so the bytes
# this script reads are not under the author's control.
ARCHIVED = ("https://web.archive.org/web/20260927234348id_/"
            "https://lostinconsoles.com/sitemap.xml")
LIVE = "https://lostinconsoles.com/sitemap.xml"
UA = "lostinconsoles-audit-verify/1.0 (+https://github.com/)"

# What the audit claims, stated so a mismatch is a failure and not a surprise.
CLAIMED_TOTAL = 2264
CLAIMED_SECTIONS = {           # prefix -> count of <loc> entries beginning with it
    "/consoles": 590,          # 589 profile pages + the /consoles hub
    "/games": 1501,            # 1,500 game pages + the /games hub
    "/blog": 68,               # 67 posts + the /blog hub
    "/comparisons": 64,
    "/best": 17,
    "/raised": 15,
}
CLAIMED_SINGLES = 9            # root + 8 named standalone pages


def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=90) as r:
        return r.read()


def locs(xml_bytes):
    return re.findall(r"<loc>\s*([^<\s]+)\s*</loc>", xml_bytes.decode("utf-8", "replace"))


def distribution(urls):
    """Count URLs beginning with each section prefix, plus everything else.

    Counting convention (stated in the course, Appendix A.1): a section's figure
    is the number of <loc> entries whose path BEGINS WITH the prefix. That
    includes the bare hub page -- e.g. /consoles/ = 589 profile pages + the
    /consoles hub = 590. The 'singles' are the root and named standalone pages.
    """
    sections = {}
    singles = []
    for u in urls:
        path = re.sub(r"^https?://[^/]+", "", u)
        hit = None
        for prefix in CLAIMED_SECTIONS:
            # a section's URLs are the prefix itself (the hub) or the prefix + "/"
            if path == prefix or path.startswith(prefix + "/"):
                hit = prefix
                break
        if hit:
            sections[hit] = sections.get(hit, 0) + 1
        else:
            singles.append(path)
    return sections, singles


def main():
    fails = []

    print("Fetching the archived sitemap (not the author's copy) ...")
    archived = fetch(ARCHIVED)
    print(f"  archived bytes: {len(archived)}  sha256: {hashlib.sha256(archived).hexdigest()}")
    a_urls = locs(archived)
    print(f"  archived <loc> entries: {len(a_urls)}")

    print("\nFetching the live sitemap for comparison ...")
    try:
        live = fetch(LIVE)
        l_urls = locs(live)
        print(f"  live <loc> entries: {len(l_urls)}")
        print(f"  archived == live (as a set): {set(a_urls) == set(l_urls)}")
        if set(a_urls) != set(l_urls):
            fails.append("archived and live sitemaps differ -- the audit's basis moved")
    except Exception as e:                                   # noqa: BLE001
        print(f"  live fetch failed ({e}) -- continuing on the archived copy alone")

    # --- headline figure 1: total ---
    total = len(a_urls)
    print(f"\n[1] Total indexable URLs: claimed {CLAIMED_TOTAL}, computed {total}")
    if total != CLAIMED_TOTAL:
        fails.append(f"total: claimed {CLAIMED_TOTAL}, got {total}")

    # --- headline figure 2: the per-section distribution ---
    sections, singles = distribution(a_urls)
    print("\n[2] Path-segment distribution:")
    ok = True
    for prefix, claimed in CLAIMED_SECTIONS.items():
        got = sections.get(prefix, 0)
        mark = "ok " if got == claimed else "MISMATCH"
        if got != claimed:
            ok = False
            fails.append(f"{prefix}: claimed {claimed}, got {got}")
        print(f"    {mark} {prefix:<12} claimed {claimed:>5}  computed {got:>5}")
    print(f"    singles (root + named standalone pages): {len(singles)}  "
          f"[claimed {CLAIMED_SINGLES}]")
    if len(singles) != CLAIMED_SINGLES:
        fails.append(f"singles: claimed {CLAIMED_SINGLES}, got {len(singles)}")
    if singles:
        print(f"      {sorted(singles)}")

    # --- headline figure 3: the arithmetic reconciles ---
    section_sum = sum(sections.values())
    grand = section_sum + len(singles)
    print(f"\n[3] Arithmetic: sections {section_sum} + singles {len(singles)} = {grand}")
    if grand != total:
        fails.append(f"distribution does not sum to the total: {grand} != {total}")
    if grand != CLAIMED_TOTAL:
        fails.append(f"distribution sums to {grand}, audit claims {CLAIMED_TOTAL}")

    print("\n" + "=" * 62)
    if fails:
        print("AUDIT DOES NOT REPRODUCE. Mismatches:")
        for f in fails:
            print("  - " + f)
        return 1
    print("AUDIT REPRODUCES: all three headline figures confirmed independently,")
    print("from an archived copy the author cannot edit.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
