"""python -B balance_334.py EVIDENCE OUTPUT.json.gz. Standard library. All optimization in half pixels."""
from collections import defaultdict
from itertools import combinations,pairwise
from statistics import median
from random import Random
from pathlib import Path
import gzip,json,hashlib,sys
def optimize(w,g,cap,old,rag):
 # All dimensions here are integers in units of half pixels. State (k,j) is a
 # feasible k-line layout of j cells; future cost depends only on this state.
 n=len(w);q=len(old);D={(0,0):(0,1,0,())};oldset=set(old);fit=defaultdict(list)
 def wide(i,j):return sum(w[i:j])+sum(g[i:j-1])
 for i in range(n):
  for j in range(i+1,n+1):
   v=wide(i,j)
   if v>cap:break
   fit[i].append((j,v))
 for k in range(q):
  for i in range(n):
   state=D.get((k,i))
   if state is None:continue
   cost,ties,mv,hist=state
   for j,v in fit[i]:
    if (k==q-1)!=(j==n) or q-k-1>n-j:continue
    z=cost+(0 if rag and j==n else (cap-v)**2);a=mv+int(j not in oldset)
    newhist=hist+(j,);s=D.get((k+1,j))
    if s is None or z<s[0]:D[k+1,j]=(z,ties,a,newhist)
    elif z==s[0]:
     h=min((a,newhist),(s[2],s[3]));D[k+1,j]=(s[0],ties+s[1],h[0],h[1])
 last=D.get((q,n))
 if last is None:return None
 best,ties,mv,ends=last
 def score(c):
  widths=[wide(i,j) for i,j in pairwise((0,*c))]
  if max(widths)>cap:return None
  return sum((cap-v)**2 for v in (widths[:-1] if rag else widths))
 os=score(old)
 assert len(ends)==q and ends[-1]==n and score(ends)==best and len(oldset-set(ends))==mv
 if os is None:return dict(bestq=best,ties=ties,min_changed=mv)
 better=[]
 for i in range(q-1):
  for delta in [-1,1]:
   alt=list(old);alt[i]+=delta
   if min(b-a for a,b in pairwise((0,*alt)))<1:continue
   v=score(alt)
   if v is not None and v<os:better.append(dict(boundary=i+1,move=delta,decrease=(os-v)/4))
 return dict(bestq=best,printedq=os,ties=ties,min_changed=mv,printed_cost=os/4,best_cost=best/4,best_counts=[b-a for a,b in pairwise((0,*ends))],printed_widths=[wide(i,j)/2 for i,j in pairwise((0,*old))],best_widths=[wide(i,j)/2 for i,j in pairwise((0,*ends))],improving_one_cell_moves=better)
def brute():
 rng=Random(334);ct=0
 for k in range(100):
  n=rng.randrange(4,11);q=rng.randrange(2,n);w=[rng.randint(4,20) for _ in range(n)];g=[rng.randint(1,8) for _ in range(n-1)]
  old=tuple(sorted(rng.sample(range(1,n),q-1)))+(n,);cap=rng.randint(max(w),sum(w))
  for rag in [False,True]:
   out=optimize(w,g,cap,old,rag);samples=[]
   for c in combinations(range(1,n),q-1):
    oc=(*c,n);s=[sum(w[i:j])+sum(g[i:j-1]) for i,j in pairwise((0,*oc))]
    if max(s)<=cap:samples.append((sum((cap-x)**2 for x in (s[:-1] if rag else s)),len(set(c)-set(old))))
   if not samples:assert out is None
   else:
    a=min(p[0] for p in samples);b=[p[1] for p in samples if p[0]==a];assert (out['bestq'],out['ties'],out['min_changed'])==(a,len(b),min(b))
   ct+=1
 return ct
def main(d):
 p=d/'grid_geometry_245.json.gz';h=hashlib.sha256(p.read_bytes()).hexdigest();assert h=='a590966c299a942b031069cac72495f921be979f1b53177eb8b0fd793a5b7a9a'
 raw=json.loads(gzip.decompress(p.read_bytes()));A=defaultdict(list)
 for a in raw:A[a['page']].append((a['row'],a['col'],a['bbox'][0],a['bbox'][2]))
 assert [len(A[p]) for p in (49,50,51)]==[80,104,72]
 G={p:[b[2]-a[3] for a,b in pairwise(v) if a[0]==b[0]] for p,v in A.items()}
 cases=[]
 for p,rows in A.items():
  n=len(rows);o=tuple(range(8,n+1,8));w=[2*(x[3]-x[2]) for x in rows]
  other=[v for pp,ls in G.items() if pp!=p for v in ls]
  for label,f in [('low',min),('median',median),('high',max)]:
   born=f(other);g=[int(2*(b[2]-a[3] if a[0]==b[0] else born)) for a,b in pairwise(rows)]
   for width in (1192,1196,1200):
    for rag in [False,True]:
     z=optimize(w,g,2*width,o,rag);assert z and 'printed_cost' in z and all(x<=width for x in z['printed_widths'])
     cases.append(dict(page=p,mode=label,join_gap=born,width_limit=width,free_last=rag,**z))
 return dict(pin=h,brute_cases=brute(),cases=cases,note='Cost units are squared pixels (bestq/printedq are 4x cost for integer verification). Fixed page breaks and line counts; centered ink, not a font reconstruction.')
if __name__=='__main__':
 o=main(Path(sys.argv[1]));Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(o,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
