"""Count the November 2026 places check again from the two CSVs. Python 3, standard library only.

200 homes in 31 countries, drawn more often where more people live; for each home, six daily needs (one row per home and
need). For each row, each map names its nearest place of that need, or names none. The maps: ours, our previous release,
OpenStreetMap on its own, and Overture Maps. Two readers, a and b, each checked every named place against a web page,
without knowing which map had named it: right (it is there, open, and of that kind), wrong (not there, closed, or another
kind of place), or cannot tell (no page settled it).
Wrong share = wrong / (right + wrong), counted over rows, per map and reader. The 95% bands resample homes (all six rows
of a home move together; 2,000 draws, same seed and order as the original count). The paired band is for (ours minus the
other map), from the same draws. "Missed a nearer real place": among rows where some map names a place a reader found
right, the share where this map names nothing.
Usage: python3 count.py [places-run9-rows.csv places-run9-places.csv]
Place names and positions: © OpenStreetMap contributors (ODbL) and Overture Maps Foundation (their licences).
"""
import csv, random, sys

SEED, DRAWS = 0x59a11c49, 2000
MAPS = ["walkably", "walkably_previous_release", "openstreetmap", "overture"]
rows_f = sys.argv[1] if len(sys.argv) > 1 else "places-run9-rows.csv"
places_f = sys.argv[2] if len(sys.argv) > 2 else "places-run9-places.csv"

places = list(csv.DictReader(open(places_f, encoding="utf-8")))
lines = list(csv.DictReader(open(rows_f, encoding="utf-8")))
homes = {}
for r in lines:
    homes.setdefault(r["home"], set()).add(r["row"])
homes = {h: sorted(x) for h, x in homes.items()}
hlist = sorted(homes)
allrows = sorted(r for h in hlist for r in homes[h])


def count(reader):
    verdict = {p["place"]: p[f"verdict_{reader}"] for p in places}
    st = {(r["row"], r["map"]): (r["status"], verdict.get(r["place"]) if r["status"] == "named" else None) for r in lines}

    def wrong_share(sample, m):
        right = wrong = 0
        for row in sample:
            v = st[(row, m)][1]
            right += v == "right"; wrong += v == "wrong"
        return None if right + wrong == 0 else 100 * wrong / (right + wrong), right + wrong

    rng, draws, diffs = random.Random(SEED), {m: [] for m in MAPS}, {m: [] for m in MAPS[1:]}
    for _ in range(DRAWS):
        sample = [row for _ in hlist for row in homes[rng.choice(hlist)]]
        s = {m: wrong_share(sample, m)[0] for m in MAPS}
        for m in MAPS:
            if s[m] is not None: draws[m].append(s[m])
        for m in diffs:
            if s["walkably"] is not None and s[m] is not None: diffs[m].append(s["walkably"] - s[m])
    real = [r for r in allrows if any(st[(r, m)] == ("named", "right") for m in MAPS)]
    print(f"reader {reader}")
    for m in MAPS:
        s, n = wrong_share(allrows, m); d = sorted(draws[m])
        miss = 100 * sum(st[(r, m)][0] == "none" for r in real) / len(real)
        print(f"  {m:26s} decided {n:3d}  wrong {s:.1f}%  (95% band {pct(d, .025)} to {pct(d, .975)})"
              f"  missed a nearer real place {miss:.1f}%")
    for m, d in diffs.items():
        d = sorted(d); gap = round(wrong_share(allrows, "walkably")[0], 1) - round(wrong_share(allrows, m)[0], 1)
        print(f"  walkably minus {m}: {gap:+.1f} points (paired 95% band {pct(d, .025)} to {pct(d, .975)})")


def pct(v, q): return round(v[min(len(v) - 1, int(q * len(v)))], 1)


print(f"homes {len(hlist)}, rows {len(allrows)}, places {len(places)}")
for reader in ("a", "b"):
    count(reader)
