"""Draw the period-8 witness from Session 164. Python 3, matplotlib; run beside layout_164_minimum.json."""
from pathlib import Path
import json,sys
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from line_mechanism_108 import D,geometry
matplotlib.rcParams.update({'svg.fonttype':'none','svg.hashsalt':'layout164-p2','font.family':'DejaVu Sans','font.size':11})
w=json.loads((D/'layout_164_minimum.json').read_text())['guarantees']['8']['2'];v=w['witness'];p=v['page'];a=v['start'];j=v['relative_slot'];n=w['min_all'];G,W=geometry()
words=[(u['page_rune_offset'],u['page_rune_offset']+len(u['values'])) for u in W if u['page']==p and u['geo'][-1][0]==p]
fig,ax=plt.subplots(figsize=(8.5,3.35));fig.subplots_adjust(top=.8,left=.14,right=.97,bottom=.24);ax.set_xlim(0,n+.35);ax.set_ylim(-.55,1.65)
for row,L in [(1,n-1),(0,n)]:
 for start,end in words:
    left=max(start,a);right=min(end,a+L)
    if right<=left:continue
    complete=start>=a and end<=a+L;hit=any((i-a)%8==j for i in range(left,right));color=('#287267' if hit else '#a4c9bf') if complete else '#e1e4e4'
    ax.add_patch(Rectangle((left-a,row-.18),right-left,.36,facecolor=color,edgecolor='white',lw=1.4))
 for i in range(j,L,8):ax.plot(i+.5,row,'o',color='#47271d',markersize=4)
ax.set_yticks([0,1],['39 runes','38 runes']);ax.set_xticks([0,8,16,24,32,39]);ax.set_xlabel('Position from window start · LP2 page 2, zero-based offset 126')
ax.set_title('One final rune completes a second word',loc='left',fontweight='bold',fontsize=17,pad=15)
for sp in ax.spines.values():sp.set_visible(False)
ax.tick_params(length=0);fig.text(.14,.055,'Dots: key slot 7    ·    Dark green: complete word touching it    ·    Gray: cut word',fontsize=10)
fig.savefig(sys.argv[1],format='svg',metadata={'Date':None});plt.close(fig)

from pathlib import Path
artifact=Path(sys.argv[1]);artifact.write_text('\n'.join(line.rstrip() for line in artifact.read_text().splitlines())+'\n')
