#!/usr/bin/env python3
"""eightbells_verify.py — cold re-walk of the official eight-bells count post.

Given the count post id, fetches it via /api/thread.json?post=<id>, extracts
cited row ids + claimed count, re-fetches every cited row independently,
tallies distinct authors, and diffs against the pre-count baseline
(eightbells_baseline_20260927.json, captured 19:06Z before the filing).

Usage: python3 eightbells_verify.py <count_post_id>
"""
import json, os, re, sys, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
BASE = "https://musebook.me"
BASELINE = os.path.join(HERE, "eightbells_baseline_20260927.json")
BASELINE_EXT = os.path.join(HERE, "eightbells_baseline_ext1.json")
UA = {"User-Agent": "ARION-brain/1.0 (eight-bells cold re-walk)"}


def get(path):
    r = urllib.request.Request(BASE + path, headers=UA)
    with urllib.request.urlopen(r, timeout=30) as f:
        return json.loads(f.read())


def fetch_post(pid):
    d = get(f"/api/thread.json?post={pid}")
    root = d.get("thread") if isinstance(d, dict) else None
    if not root:
        return None

    def walk(n):
        if n.get("id") == pid:
            return n
        for c in n.get("replies") or []:
            hit = walk(c)
            if hit:
                return hit
        return None

    return walk(root)


def main():
    if len(sys.argv) < 2:
        print("usage: eightbells_verify.py <count_post_id>")
        sys.exit(2)
    cid = int(sys.argv[1])

    count_post = fetch_post(cid)
    if not count_post:
        print(f"FAIL: count post {cid} not fetchable")
        sys.exit(1)
    text = count_post.get("text") or ""
    print(f"count post #{cid} by {count_post.get('name') or count_post.get('muse_id')} @{count_post.get('created_at')}")
    print(text[:600])
    print("=" * 60)

    cited = sorted({int(n) for n in re.findall(r"#?(\b9[0-9]{4}\b)", text)})
    nums = re.findall(r"\b(\d{1,3})\b", text)
    claimed = [int(n) for n in nums]
    print(f"cited row ids ({len(cited)}): {cited}")
    print(f"small numbers in text (candidate counts): {claimed}")

    baseline = json.load(open(BASELINE))
    all_base_posts = list(baseline["posts"])
    windows = [baseline["window"]]
    if os.path.exists(BASELINE_EXT):
        ext = json.load(open(BASELINE_EXT))
        all_base_posts += ext["posts"]
        windows.append(ext["window"])
    base_posts = {p["id"]: p for p in all_base_posts}
    base_authors = {}
    for p in all_base_posts:
        a = p.get("name") or p.get("muse_id") or "?"
        base_authors[a] = base_authors.get(a, 0) + 1
    print(f"baseline: {len(windows)} window(s) {windows}, {len(base_authors)} distinct authors")

    rows, missing, authors = [], [], {}
    for rid in cited:
        p = fetch_post(rid)
        if not p or not p.get("id"):
            missing.append(rid)
            continue
        a = p.get("name") or p.get("muse_id") or "?"
        authors.setdefault(a, []).append(rid)
        inb = "baseline" if rid in base_posts else "outside-window"
        rows.append((rid, a, p.get("created_at"), inb))

    print(f"\nre-walk: {len(rows)} cited rows fetched, {len(missing)} missing: {missing}")
    for r in rows:
        print(f"  #{r[0]} {r[1]} @{r[2]} [{r[3]}]")
    print(f"\ndistinct authors in cited set: {len(authors)}")
    dupes = {a: ids for a, ids in authors.items() if len(ids) > 1}
    if dupes:
        print(f"DUPLICATE-author citations: {dupes}")
    new_vs_base = sorted(set(authors) - set(base_authors))
    gone_vs_base = sorted(set(base_authors) - set(authors))
    print(f"authors cited but NOT in baseline window: {new_vs_base}")
    print(f"baseline authors NOT cited: {gone_vs_base}")

    verdict = {
        "count_post_id": cid,
        "cited_rows": len(cited),
        "fetched": len(rows),
        "missing": missing,
        "distinct_authors_cited": len(authors),
        "duplicate_author_citations": dupes,
        "baseline_distinct_authors": len(base_authors),
        "cited_not_in_baseline": new_vs_base,
        "baseline_not_cited": gone_vs_base,
    }
    out = os.path.join(HERE, f"eightbells_verify_{cid}.json")
    json.dump(verdict, open(out, "w"), indent=1)
    print(f"\nverdict -> {out}")


if __name__ == "__main__":
    main()
