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

Each row is one home and one daily need (1,134 rows, 31 countries). For each row, each of three maps names its nearest
place of that need, or names none. Each named place was checked against a web page: 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. The 95% bands resample rows within their group
(2,000 draws, same seed and order as the original count). The paired band is for (Walkably minus the other map), from the
same draws. Usage: python3 count.py [places-run7-rows.csv places-run7-places.csv]
Place names and positions: © OpenStreetMap contributors (ODbL) and Overture Maps Foundation (their licences).
"""
import csv, random, sys

SEED, DRAWS, MAPS = 0x95b2de77, 2000, ["walkably", "openstreetmap", "overture"]
GROUPS = ["A0", "A1", "F0", "F1"]
rows_f = sys.argv[1] if len(sys.argv) > 1 else "places-run7-rows.csv"
places_f = sys.argv[2] if len(sys.argv) > 2 else "places-run7-places.csv"

verdict = {p["place"]: p["verdict"] for p in csv.DictReader(open(places_f, encoding="utf-8"))}
st, group = {}, {}
for r in csv.DictReader(open(rows_f, encoding="utf-8")):
    st[(r["row"], r["map"])] = verdict[r["place"]] if r["status"] == "named" else None
    group[r["row"]] = r["group"]
by_group = {g: sorted(x for x in group if group[x] == g) for g in GROUPS}


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


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


rng, draws, diffs = random.Random(SEED), {m: [] for m in MAPS}, {m: [] for m in MAPS[1:]}
for _ in range(DRAWS):
    sample = [rng.choice(by_group[g]) for g in GROUPS for _ in by_group[g]]
    s = {m: 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])
allrows = sorted(group)
print(f"rows {len(allrows)}, places {len(verdict)}")
for m in MAPS:
    s, n = share(allrows, m); d = sorted(draws[m])
    print(f"{m:14s} decided {n:3d}  wrong {s:.1f}%  (95% band {pct(d, .025)} to {pct(d, .975)})")
for m, d in diffs.items():
    d = sorted(d); gap = round(share(allrows, "walkably")[0], 1) - round(share(allrows, m)[0], 1)
    print(f"walkably minus {m}: {gap:+.1f} points (paired 95% band {pct(d, .025)} to {pct(d, .975)})")
