"""Verify certificates with integer arithmetic. Pass the saved JSON files as arguments."""
import itertools
import json
from collections import defaultdict
from math import gcd
from pathlib import Path
import sys

def verify(record):
    n, color, Q = (record[k] for k in ('n','color','denominator'))
    assert Q > 0 and n>0 and n%2==1 and color in (0,1)
    r = n//2
    board = {(x,y) for x in range(-r,r+1) for y in range(-r,r+1) if (x+y)%2==color}
    pts = record['point_masses']
    assert len({(x,y) for x,y,w in pts})==len(pts)
    assert all((x,y) in board and type(w) is int and 0<w<=Q for x,y,w in pts)
    lower = sum(w for _,_,w in pts)
    for i,(x,y,w) in enumerate(pts):
        by_direction=defaultdict(int)
        for u,v,mass in pts[i+1:]:
            dx,dy=u-x,v-y
            g=gcd(dx,dy)
            if dx<0 or (not dx and dy<0):
                g=-g
            by_direction[dx//g,dy//g]+=mass
        assert all(s+w<=2*Q for s in by_direction.values())
    for prefix in ('four_',''):
        cover=defaultdict(int)
        upper=0
        for a,b,c,w in record[prefix+'line_dual']:
            assert not prefix or (a,b) in ((0,1),(1,1))
            assert 0<=a<=b and gcd(a,b)==1 and c>=0 and type(w) is int and w>=0
            normals={(u,v) for u,v in itertools.permutations((a,b)) for v in [v,-v] if u>0 or (u==0 and v>0)}
            for u,v in normals:
                for k in {c,-c}:
                    upper+=2*w
                    for x,y in board:
                        if u*x+v*y==k: cover[x,y]+=w
        for (a,b),w in record[prefix+'point_dual']:
            assert 0<=a<=b and type(w) is int and w>=0
            for x,y in board:
                if sorted((abs(x),abs(y)))==[a,b]:
                    cover[x,y]+=w
                    upper+=w
        assert all(cover[p]>=Q for p in board)
        assert lower==record['lower_numerator']<=record[prefix+'upper_numerator']==upper
    print(n,color,lower,upper,Q,flush=True)
if __name__=='__main__':
    for name in sys.argv[1:]:
        records = json.loads(Path(name).read_text())
        for record in records if isinstance(records,list) else [records]:
            verify(record)
