"""Replay: python -B marks_235.py [notebook /files source directory] [output directory].
Uses NumPy, SciPy, Pillow. Reads only archival images, transcription, prior image hashes and fixed selection.
Freeze decoding and analysis choices outside this script: it sees only rune membership, never ordinal values.
"""
from collections import defaultdict
from pathlib import Path
import hashlib,json,re,sys
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from scipy import ndimage
HERE=Path(__file__).resolve().parent
SRC=Path(sys.argv[1]) if len(sys.argv)>1 else HERE
OUT=Path(sys.argv[2]) if len(sys.argv)>2 else HERE
R=set('ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ')
def sha(f):return hashlib.sha256(f.read_bytes()).hexdigest()
def load(f):return json.loads(f.read_text())
def write(f,d):f.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n')
# Only archival image names and byte hashes are used from the earlier inventory.
inventory={p['page']:p for p in load(SRC/'illustrated_transition_results.json')['inventory']}
fr=load(HERE/'marks_235_freeze.json')
master=SRC/'liber-primus__transcription--master.txt'
assert sha(master)=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
raw=master.read_text();pg=raw[raw.index('ᚱ-'):].split('%')[15:];ln=lambda s:sum(c in R for c in s)
assert sum(map(ln,pg[:40]))==9640
thresholds=[(145,85),(130,100),(115,115)]
events=[];pages={};offset=0;amps=[];seen=[]
for p in range(40,56):
    fn=SRC/f'{p+17}.jpg';assert sha(fn)==inventory[p]['sha256']
    a=np.asarray(Image.open(fn).convert('RGB')); assert a.shape==(3600,2400,3)
    def analyze(lo,hi):
        red=(a[:,:,0]>lo)&(a[:,:,1]<hi)&(a[:,:,2]<hi)
        # 4-connected components in a mask. A small detached dot lies in a 6..15 px square.
        lab,n=ndimage.label(red);sl=ndimage.find_objects(lab);areas=np.bincount(lab.ravel())
        boxes=[];big=[]
        for i,it in enumerate(sl,1):
            if it is None:continue
            y,x=it;w=x.stop-x.start;h=y.stop-y.start
            if 6<=w<=15 and 6<=h<=15 and areas[i]>=24:
                boxes.append((x.start,y.start,x.stop,y.stop))
            if h>=75 and areas[i]>=300:big.append((x.start,y.start,x.stop,y.stop))
        # A chain of near-neighbour small dots defines a mark, ignoring isolated separators.
        group=[];todo=set(range(len(boxes)))
        while todo:
            q=[min(todo)];todo.remove(q[0]);component=[]
            while q:
                i=q.pop();b=boxes[i];component.append(b)
                for j in list(todo):
                    v=boxes[j]
                    if abs((b[0]+b[2])-(v[0]+v[2]))<=38 and abs((b[1]+b[3])-(v[1]+v[3]))<=44:
                        todo.remove(j);q.append(j)
            if len(component)>=4:
                x0=min(t[0] for t in component); y0=min(t[1] for t in component)
                x1=max(t[2] for t in component); y1=max(t[3] for t in component)
                group.append({'count':len(component),'box':[x0,y0,x1,y1],'dot_boxes':sorted(component)})
        return {'red_pixel_count':int(red.sum()),'multidot':sorted(group,key=lambda v:(v['box'][1],v['box'][0])),
                'tall_red_components':big}
    scans={f'R>{lo};G,B<{hi}':analyze(lo,hi) for lo,hi in thresholds}
    base=scans['R>130;G,B<100']; bcount=[v['count'] for v in base['multidot']]
    for row in scans.values():assert [v['count'] for v in row['multidot']]==bcount
    assert bcount=={49:[10],53:[13],54:[13],55:[13]}.get(p,[])
    if p not in [40,49,53,54,55]: assert all(not row['red_pixel_count'] for row in scans.values())
    if base['tall_red_components']:seen.append(p)
    punct=[];i=0
    for c in pg[p]:
        if c in R:i+=1
        elif c in '.&$':punct.append([i,c])
    amps.extend([offset+i for i,c in punct if c=='&'])
    pages[p]=dict(section_offset=offset,runes=i,original_file=fn.name,sha256=sha(fn),
        original_url=f'https://github.com/iBotPeaches/cicada_3301/blob/master/liber_primus/{fn.name}',
        physical_scan=scans,transcription_stops_paragraphs_and_sections=punct)
    offset+=i
# All red glyphs, as distinct from red dots, are on three pages.
assert seen==[40,53,54] and offset==3316
assert amps==[2474,2474,3008,3316]
assert fr['primary_cuts']==sorted(set(amps)-{0,3316})
# Independent manual alignment check for the newly localized start of the closing color span.
# The first red glyph in the physical page 53 crop is the LAST glyph on manuscript line six.
lines53=[v for v in pg[53].split('/') if ln(v)]
page53_red_start=sum(map(ln,lines53[:6]))-1
assert page53_red_start==128 and ln(pg[53])-page53_red_start==51
t0=pages[53]['physical_scan']['R>130;G,B<100']['tall_red_components']
assert sum(1 for b in t0 if 1620<=b[1]<1780)==1 and min(t[1] for t in t0)>=1620
assert any((j,c)==(128,'.') for j,c in pages[53]['transcription_stops_paragraphs_and_sections'])
# The red passage is preceded by a black, not a red, mark; reproduce its four squares.
black53={}
for t in (80,100,120):
    g=np.asarray(Image.open(SRC/'70.jpg').convert('L'))[1642:1780,1650:1720]<t
    labs,_=ndimage.label(g)
    boxes=[[u.start+1650,v.start+1642,u.stop+1650,v.stop+1642] for v,u in ndimage.find_objects(labs)
           if 6<=u.stop-u.start<=14 and 6<=v.stop-v.start<=14]
    assert len(boxes)==4;black53[t]=boxes
# Prior independently reviewed spans from 57, use geometry fields only and do not read any analysis.
old=load(SRC/'heading_change_results.json')['visual_openers']
sps={v['page']:v['page_rune_span'] for v in old if v['page'] in (40,54)}
assert sps=={40:[0,8],54:[0,9]}
colored=[[40,0,8],[53,128,179],[54,0,9]]
assert sorted(set(fr['primary_cuts'])|{pages[40]['section_offset']+8,pages[53]['section_offset']+page53_red_start,pages[54]['section_offset']+9})==fr['secondary_cuts']
for off,p,i,role in fr['events']:
    assert pages[p]['section_offset']+i==off
    events.append(dict(local=off,global_gap=9640+off,page=p,page_gap=i,role=role,
                       primary=off in fr['primary_cuts'],secondary=off in fr['secondary_cuts']))
# Every actual pixel panel is a rectangular crop of the full image; no recoloring.
panels=[
 (40,(580,640,1540,890),'0 / 8   |   page 40','Opening red words pass into black at a single dot.'),
 (49,(805,1015,1775,1360),'2,474   |   page 49','Black runes stop at ten red dots; the grid begins below.'),
 (51,(590,2040,1730,2430),'2,474   |   page 51','The grid ends above black runes, with no red mark.'),
 (53,(1080,1620,1798,1800),'2,957   |   page 53','The closing red passage starts with the last rune of line six.'),
 (53,(585,2220,1055,2400),'3,008   |   page 53','Thirteen red dots close the red passage, above an illustration.'),
 (54,(580,885,1515,1080),'3,008 / 3,017   |   page 54','A large initial opens a red heading; thirteen dots introduce black text.'),
 (55,(580,1210,1110,1390),'3,316   |   page 55','Thirteen red dots close the section; no following rune resets here.')]
def contact():
    def font(sz,bold=False):
        name='DejaVuSans-Bold.ttf' if bold else 'DejaVuSans.ttf'
        try:return ImageFont.truetype(name,sz)
        except OSError:return ImageFont.load_default()
    out=Image.new('RGB',(1440,985),'white');d=ImageDraw.Draw(out)
    d.text((26,13),'Section 8  /  what the printed boundaries look like',font=font(29,True),fill='#192b34')
    d.text((26,54),'LP2 page numbers; offsets count runes from page 40. Source crops have been scaled to fit.',font=font(18),fill='#42515b')
    for index,(p,box,label,cap) in enumerate(panels):
        x=22+(index%2)*710; y=108+index//2*218
        d.text((x,y),label,font=font(23,True),fill='#192b34')
        im=Image.open(SRC/f'{p+17}.jpg').crop(box);im.thumbnail((660,126),Image.Resampling.LANCZOS)
        out.paste(im,(x+5,y+34+(126-im.height)//2))
        d.text((x,y+171),cap,font=font(16),fill='#42515b')
    out.save(OUT/'marks_235_contact.jpg',quality=91,optimize=True)
contact()
write(OUT/'marks_235_evidence.json',dict(freeze_sha256=sha(HERE/'marks_235_freeze.json'),master_sha256=sha(master),
    section_length=offset,section_global_start=9640,primary_cuts=fr['primary_cuts'],secondary_cuts=fr['secondary_cuts'],
    events=events,editorial_ampersand_offsets_with_multiplicity=amps,red_rune_spans_page_half_open=colored,pages=pages,
    contact_panels=panels,black_mark_before_page53_red_rune=black53,
    caveat='Mark presence is image evidence; mapping glyphs to rune gaps is manual alignment with the pinned transcription, not independent OCR. The grid consumes no rune in this coordinate system. No cryptographic reset observed.'))
print('Primary',fr['primary_cuts'],'; color sensitivity',fr['secondary_cuts'],'; 4 red multidot clusters on 16 pages.')
