"""Reproduce the four-day descriptive results. Run with Python 3 from any directory."""
import json
from collections import Counter
from pathlib import Path
from statistics import median

root = Path(__file__).resolve().parents[1]
packed = (root / "review-archive.js").read_text().strip()
archive = json.loads(packed.removeprefix("const reviewArchive = ").removesuffix(";"))
saved = {}
for day in range(1, 5):
    path = root / "reviews" / f"2024-07-{day:02}-day" / "scores.json"
    for row in json.loads(path.read_text()):
        saved[day, row["hour"], row["rank"]] = row

south = Counter()
north = Counter()
paired = Counter()
costs = []
stays = 0
for c in archive:
    row = saved[c["day"], c["hour"], c["rank"]]
    def xy(i):
        return i % c["w"], i // c["w"]
    radar = set(map(xy, c["r"]))
    satellite = set(map(xy, c["s"]))
    originally_shared = radar & satellite
    def patch(center):
        x, y = center
        return {p for p in originally_shared if max(abs(p[0]-x), abs(p[1]-y)) <= 1}
    interior, southern = [patch(xy(i)) for i in c["centers"]]
    # Change only the edge center rule. Rows increase southward.
    northern = patch(min(originally_shared, key=lambda p: (p[1], p[0])))
    positions = []
    for dy in range(-5, 6):
        for dx in range(-5, 6):
            shifted = {(x+dx, y+dy) for x, y in satellite}
            matched = radar & shifted
            key = (-len(matched), len(originally_shared - matched), dx*dx + dy*dy, dy, dx)
            positions.append((key, dx, dy, len(matched)/len(radar | shifted), matched))
    positions.sort(key=lambda p: p[0])
    def best(required):
        return next(p for p in positions if required <= p[4])
    free = positions[0]
    for name, cells in [('free', set()), ('interior_only', interior), ('edge_only', southern), ('both', interior | southern)]:
        _, dx, dy, iou, _ = best(cells)
        assert (dx,dy,iou) == tuple(row[name][k] for k in ('dx','dy','iou'))
    if not c["strict"]:
        continue
    def attribution(edge):
        loses_i = not interior <= free[4]
        loses_e = not edge <= free[4]
        return ('neither','interior only','edge only','both independently')[int(loses_i) + 2*int(loses_e)]
    s, n = attribution(southern), attribution(northern)
    south[s] += 1
    north[n] += 1
    paired[s != 'neither', n != 'neither'] += 1
    if s != 'neither':
        joint = best(interior | southern)
        costs.append(100 * (free[3] - joint[3]))
        stays += int(joint[1:3] == (0,0))

print("Strict reviews", sum(south.values()))
print("Original southern rule", dict(south))
print("Exploratory northern rule", dict(north))
print("Changes (south, north)", dict(paired))
print("Median overlap cost among changed decisions (percentage points)", median(costs))
print("Equal score", costs.count(0), "stay", stays, "alternate moving shift", len(costs)-stays)
