"""Make the control grid figure from the compact S240/241 evidence file. No plotting libraries required."""
from pathlib import Path
import json,gzip
D=Path(__file__).resolve().parent
z=json.loads(gzip.decompress((D/'marks_240_241_results.json.gz').read_bytes()))
svg=['<svg xmlns="http://www.w3.org/2000/svg" width="900" height="455" viewBox="0 0 900 455" role="img" aria-labelledby="title desc">','<title id="title">Nonidentity keys at ordinary word boundaries near the actual marks</title><desc id="desc">Each cell counts admissible ordered keys with the two indicated shifts in reset position. Twenty-seven of sixty-four layouts pass at period eight, thirty-five at period nine.</desc>','<rect width="900" height="455" fill="#faf8f3"/>']
def label(x,y,t,size=14,fill='#222e32',anchor='start',weight='normal'):
    svg.append(f'<text x="{x}" y="{y}" font-family="system-ui,sans-serif" font-size="{size}" fill="{fill}" text-anchor="{anchor}" font-weight="{weight}">{t}</text>')
label(24,32,'Moving both resets to nearby ordinary word boundaries',24,weight='bold')
label(24,57,'Each cell is the number of surviving nonidentity keys; axes show displacement in runes.',15)
ds=[[i-z['coords']['primary'][a] for i in v] for a,v in enumerate(z['coords']['word']['choices'])]
for pi,p in enumerate(('8','9')):
    ox=115+pi*430;oy=134;w=33
    label(ox,90,f'Period {p}  ·  {27 if p=="8" else 35}/64 layouts pass',18,weight='bold')
    label(ox+120,110,'Second reset shift',13,anchor='middle')
    for j,dx in enumerate(ds[1]):label(ox+w*(j+0.5),127,f'{dx:+d}',12,anchor='middle')
    for i,dy in enumerate(ds[0]):
        label(ox-8,oy+w*(i+.5)+4,f'{dy:+d}',12,anchor='end')
        for j in range(8):
            n=len(z['nonidentity_keys'][p][1+8*i+j]);fill=['#e6e4dc','#cae1dc','#85c3b9','#468b7b','#255f54'][n]
            svg.append(f'<rect x="{ox+j*w+1}" y="{oy+i*w+1}" width="{w-2}" height="{w-2}" rx="3" fill="{fill}"/>')
            label(ox+w*(j+.5),oy+w*(i+.5)+5,str(n),14,fill='#fff' if n>=3 else '#23382f',anchor='middle')
    svg.append(f'<text transform="translate({ox-51} {oy+4*w}) rotate(-90)" text-anchor="middle" font-family="system-ui,sans-serif" fill="#222e32" font-size="13">First reset shift</text>')
label(24,430,'The actual marked pair (0, 0) permits one nonidentity key at each period.',15)
svg.append('</svg>');(D/'marks_240_comparison.svg').write_text('\n'.join(svg)+'\n')
