"""Session74: bounded glyph recognition with separate reading and evaluation.
Python + NumPy + SciPy + Pillow. Originals remain unchanged.
prepare uses declared training/development truth; read never imports lp_core.
"""
from pathlib import Path
from collections import Counter
import argparse, hashlib, json
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage

ROOT=Path(__file__).resolve().parent
LET='F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
SETTINGS={'x0':580,'x1':1840,'y0':620,'y1':2940,'black_max':140,
          'max_channel_spread':30,'minimum_component_pixels':500,'row_ink_threshold':20,
          'minimum_row_height':90,'maximum_row_height':150,
          'minimum_glyph_width':8,'maximum_glyph_width':100,
          'normal_height':96,'canvas':128,'maximum_training_row_red_pixels':500,
          'connectivity':8}
END_OVERRIDES={'05.jpg':1450,'09.jpg':1610,'13.jpg':1000}
DISTANCES=[.03,.05,.075,.10,.15,.20]
MARGINS=[.01,.025,.05,.075,.10]

def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def readjson(name):return json.loads((ROOT/name).read_text())
def writejson(name,obj):(ROOT/name).write_text(json.dumps(obj,indent=2)+'\n')

def bands(v):
    ix=np.flatnonzero(v)
    return [(int(g[0]),int(g[-1])+1) for g in np.split(ix,np.flatnonzero(np.diff(ix)>1)+1) if len(g)]

def segment(image,settings=SETTINGS):
    s=settings;end=END_OVERRIDES.get(image,s['y1'])
    a=np.asarray(Image.open(ROOT/image).convert('RGB'))[s['y0']:end,s['x0']:s['x1']].astype(int)
    ink=(a.max(axis=2)<s['black_max']) & (a.max(axis=2)-a.min(axis=2)<s['max_channel_spread'])
    mask=ink.copy();structure=np.ones((3,3),dtype=bool)
    labels,_=ndimage.label(mask,structure=structure);sizes=np.bincount(labels.ravel());keep=np.zeros(len(sizes),dtype=bool)
    # Apply bounds before row cropping so long illustration/frame fragments
    # cannot be sliced into apparently letter-height pieces.
    for k,bb in enumerate(ndimage.find_objects(labels),1):
        if bb is None:continue
        y,x=bb;h=y.stop-y.start;w=x.stop-x.start
        keep[k]=(sizes[k]>=s['minimum_component_pixels'] and
                 s['minimum_row_height']<=h<=s['maximum_row_height'] and
                 s['minimum_glyph_width']<=w<=s['maximum_glyph_width'])
    mask &= keep[labels]
    rows=[]
    for lo,hi in bands(mask.sum(axis=1)>s['row_ink_threshold']):
        if not s['minimum_row_height']<=hi-lo<=s['maximum_row_height']:continue
        cut=mask[lo:hi];labels,_=ndimage.label(cut,structure=structure);glyphs=[]
        for k,bb in enumerate(ndimage.find_objects(labels),1):
            if bb is None:continue
            y,x=bb;h=y.stop-y.start;w=x.stop-x.start
            if not (s['minimum_row_height']<=h<=s['maximum_row_height'] and
                    s['minimum_glyph_width']<=w<=s['maximum_glyph_width']):continue
            # Preserve disconnected interior strokes inside a glyph's box.
            # Component-only masks made the three-stem Y look identical to U.
            local=ink[lo:hi][bb]
            glyphs.append({'bbox':[s['x0']+x.start,s['y0']+lo+y.start,
                                   s['x0']+x.stop,s['y0']+lo+y.stop], 'mask':local})
        glyphs.sort(key=lambda g:g['bbox'][0])
        red=(a[lo:hi,:,0]>120)&(a[lo:hi,:,0]-a[lo:hi,:,1]>60)&(a[lo:hi,:,0]-a[lo:hi,:,2]>60)
        rows.append({'row':len(rows)+1,'y_span':[s['y0']+lo,s['y0']+hi],
                     'red_pixels':int(red.sum()),'glyphs':glyphs})
    return rows

def normalize(mask):
    h,w=mask.shape;nh=SETTINGS['normal_height'];nw=max(1,round(w*nh/h));size=SETTINGS['canvas']
    assert nw<=size
    im=Image.fromarray(mask.astype('uint8')*255).resize((nw,nh),Image.Resampling.BOX)
    out=np.zeros((size,size),dtype=np.uint8);x=(size-nw)//2;y=(size-nh)//2
    out[y:y+nh,x:x+nw]=np.asarray(im)
    return out

def reference_rows(image):
    # This is called only by prepare/evaluate, never by read mode.
    from lp_core import pages,R,LET as names
    assert names==LET
    n=int(image[:2]);p=0 if n==1 else n-2
    return [[R.index(ch) for ch in s if ch in R] for s in pages[p].split('/') if any(ch in R for ch in s)]

def score(mask,templates,labels):
    q=normalize(mask).astype(np.int16)
    diff=np.abs(templates.astype(np.int16)-q).sum(axis=(1,2),dtype=np.int64)
    denom=np.maximum(templates.sum(axis=(1,2),dtype=np.int64),q.sum(dtype=np.int64))
    distances=diff/np.maximum(denom,1)
    bylabel=np.array([distances[labels==k].min() for k in range(29)])
    rank=np.argsort(bylabel,kind='stable');best=int(rank[0]);second=int(rank[1])
    witness=int(np.flatnonzero(labels==best)[np.argmin(distances[labels==best])])
    return {'best_label':best,'best_name':LET[best],'distance':float(bylabel[best]),
            'second_name':LET[second],'distinct_label_margin':float(bylabel[second]-bylabel[best]),
            'prototype_index':witness}

def accepted(pred,distance,margin):
    return pred['distance']<=distance and pred['distinct_label_margin']>=margin

def prepare():
    plan=readjson('glyph_reader_plan.json');records=[];arrays=[];labels=[];discarded=[]
    for image in plan['training_images']:
        rows=segment(image);truth=reference_rows(image)
        for j,row in enumerate(rows):
            ref=truth[j] if j<len(truth) else []
            ok=len(row['glyphs'])==len(ref) and row['red_pixels']<=SETTINGS['maximum_training_row_red_pixels']
            if not ok:
                discarded.append({'image':image,'row':j+1,'detected':len(row['glyphs']),
                                  'reference':len(ref),'red_pixels':row['red_pixels'],'reason':'count mismatch or red overlap'})
                continue
            for glyph,label in zip(row['glyphs'],ref):
                arrays.append(normalize(glyph['mask']));labels.append(label)
                records.append({'image':image,'row':j+1,'bbox':glyph['bbox'],'label':label,'name':LET[label],
                                'alignment':'sequential known-row labels after count agreement; not independent training-label verification'})
    templates=np.stack(arrays);labels=np.array(labels,dtype=int)
    assert set(labels.tolist())==set(range(29)), 'Training alphabet incomplete'
    # Development scoring does not alter templates. Only declared threshold pairs are compared.
    dev=[];dev_rows=[]
    for image in plan['development_images']:
        rows=segment(image);truth=reference_rows(image)
        for j,row in enumerate(rows):
            ref=truth[j] if j<len(truth) else []
            aligned=len(ref)==len(row['glyphs']) and row['red_pixels']<=500
            dev_rows.append({'image':image,'row':j+1,'detected':len(row['glyphs']),
                             'reference':len(ref),'eligible_for_threshold_fit':aligned})
            if aligned:
                for g,label in zip(row['glyphs'],ref):
                    dev.append({'image':image,'row':j+1,'bbox':g['bbox'],'truth':label,
                                **score(g['mask'],templates,labels)})
    grid=[]
    for d in DISTANCES:
        for m in MARGINS:
            take=[p for p in dev if accepted(p,d,m)]
            grid.append({'distance':d,'margin':m,'accepted':len(take),
                         'wrong':sum(p['best_label']!=p['truth'] for p in take)})
    eligible=[g for g in grid if not g['wrong']]
    if not eligible or not dev:
        writejson('glyph74_development_failure.json',{'development_predictions':dev,
             'development_rows':dev_rows,'grid':grid,'training_records':records})
    assert eligible and dev
    chosen=sorted(eligible,key=lambda g:(-g['accepted'],g['distance'],-g['margin']))[0]
    np.savez_compressed(ROOT/'glyph74_templates.npz',templates=templates,labels=labels)
    writejson('glyph74_training.json',{'templates':records,'discarded_rows':discarded,
             'development_rows':dev_rows,'development_predictions':dev,'threshold_grid':grid,
             'threshold_choice':chosen,'training_alphabet_counts':dict(Counter(LET[v] for v in labels.tolist()))})
    # Exact native source patches, labels outside pixels, for inspection of training label quality.
    atlas=Image.new('RGB',(6*130,5*170),'white');draw=ImageDraw.Draw(atlas)
    for k,name in enumerate(LET):
        ix=next(i for i,r in enumerate(records) if r['label']==k);r=records[ix]
        patch=Image.open(ROOT/r['image']).convert('RGB').crop(r['bbox'])
        x=(k%6)*130;y=(k//6)*170;draw.text((x+4,y+4),name,fill='black')
        atlas.paste(patch,(x+4,y+28))
    atlas.save(ROOT/'glyph74_training_atlas.png')
    freeze={'session':74,'script_sha256':sha(Path(__file__)),'plan_sha256':sha(ROOT/'glyph_reader_plan.json'),
            'templates_sha256':sha(ROOT/'glyph74_templates.npz'),'training_sha256':sha(ROOT/'glyph74_training.json'),
            'settings':SETTINGS,'roi_end_overrides':END_OVERRIDES,
            'distance_limit':chosen['distance'],'minimum_distinct_label_margin':chosen['margin'],
            'training_images':plan['training_images'],'development_images':plan['development_images'],
            'held_out_images':plan['held_out_images'],'target_images':plan['conditional_target_images'],
            'fit_image_hashes':{n:sha(ROOT/n) for n in plan['training_images']+plan['development_images']},
            'training_glyphs':len(records),'training_types':29,'development_scored_glyphs':len(dev),
            'limitations':'One frozen model; count-aligned training rows only. Development exclusions retained. No target image or target reference used in fitting. Same assistant and prior source exposure remain limitations.'}
    writejson('glyph74_freeze.json',freeze)
    print(json.dumps({'training':len(records),'types':29,'development':len(dev),'chosen':chosen,
                      'discarded_training_rows':len(discarded),'freeze_sha256':sha(ROOT/'glyph74_freeze.json')},indent=2))

def load_frozen():
    f=readjson('glyph74_freeze.json')
    assert sha(Path(__file__))==f['script_sha256'],'Implementation changed after freeze'
    assert sha(ROOT/'glyph_reader_plan.json')==f['plan_sha256']
    assert sha(ROOT/'glyph74_templates.npz')==f['templates_sha256']
    assert sha(ROOT/'glyph74_training.json')==f['training_sha256']
    assert SETTINGS==f['settings'] and END_OVERRIDES==f['roi_end_overrides']
    with np.load(ROOT/'glyph74_templates.npz',allow_pickle=False) as data:
        t=data['templates'];labels=data['labels']
    return f,t,labels

def read_images(scope):
    f,t,labels=load_frozen()
    if scope=='target':
        previous=readjson('glyph74_results.json')
        assert previous['held_out_gate_passed'],'Held-out gate failed: target recognition is blocked'
        assert previous['freeze_sha256']==sha(ROOT/'glyph74_freeze.json')
    names=f['held_out_images'] if scope=='held' else f['target_images']
    pages=[]
    for image in names:
        rows=segment(image);predicted=[]
        for row in rows:
            entries=[]
            for g in row['glyphs']:
                p=score(g['mask'],t,labels);p['bbox']=g['bbox']
                p['accepted']=accepted(p,f['distance_limit'],f['minimum_distinct_label_margin'])
                p['output']=p['best_name'] if p['accepted'] else '?';entries.append(p)
            predicted.append({'row':row['row'],'y_span':row['y_span'],'red_pixels':row['red_pixels'],'predictions':entries})
        pages.append({'image':image,'source_sha256':sha(ROOT/image),'rows':predicted})
    output={'session':74,'scope':scope,'recognition_uses_transcription':False,
            'freeze_sha256':sha(ROOT/'glyph74_freeze.json'),'script_sha256':sha(Path(__file__)),
            'pages':pages,'raw_output_policy':'Image-only prediction saved before evaluation; question mark means abstention.'}
    writejson(f'glyph74_{scope}_predictions.json',output)
    print(json.dumps({'scope':scope,'images':names,'detected':sum(len(r['predictions']) for p in pages for r in p['rows']),
                      'prediction_sha256':sha(ROOT/f'glyph74_{scope}_predictions.json')},indent=2))

def evaluate(scope):
    f,t,labels=load_frozen();raw=readjson(f'glyph74_{scope}_predictions.json')
    assert raw['freeze_sha256']==sha(ROOT/'glyph74_freeze.json') and not raw['recognition_uses_transcription']
    manifest={r['file']:r['sha256'] for r in readjson('jpeg_source_manifest.json')['files']}
    metrics=[];failures=[]
    for page in raw['pages']:
        image=page['image'];assert page['source_sha256']==sha(ROOT/image)==manifest[image]
        truth=reference_rows(image);rows=page['rows'];alignment_ok=len(rows)==len(truth)
        correct=wrong=abstain=unaligned=0;details=[]
        for j in range(max(len(rows),len(truth))):
            preds=rows[j]['predictions'] if j<len(rows) else [];ref=truth[j] if j<len(truth) else []
            aligned=len(preds)==len(ref)
            alignment_ok &=aligned
            info={'row':j+1,'detected':len(preds),'reference':len(ref),'count_aligned':aligned}
            if not aligned:
                unaligned+=len(preds)
                failures.append({'image':image,'row':j+1,'reason':'segmentation count mismatch',
                                 'detected':len(preds),'reference':len(ref)})
            else:
                for position,(p,label) in enumerate(zip(preds,ref)):
                    if not p['accepted']:abstain+=1
                    elif p['best_label']==label:correct+=1
                    else:
                        wrong+=1;failures.append({'image':image,'row':j+1,'position':position,
                          'reason':'wrong accepted label','prediction':p['best_name'],'truth':LET[label],
                          'bbox':p['bbox'],'distance':p['distance'],'margin':p['distinct_label_margin']})
            details.append(info)
        expected=sum(map(len,truth));coverage=(correct+wrong)/expected
        gate=alignment_ok and wrong==0 and coverage>=.95
        metrics.append({'image':image,'reference_runes':expected,'detected':sum(len(r['predictions']) for r in rows),
          'segmentation_aligned':alignment_ok,'correct_accepted_in_count_aligned_rows':correct,
          'wrong_accepted_in_count_aligned_rows':wrong,'abstentions_in_count_aligned_rows':abstain,
          'detections_in_unaligned_rows':unaligned,'accepted_coverage_on_reference':coverage,
          'page_gate_passed':gate,'rows':details})
    # Separate mathematical recovery fixtures, not a substitute for held-out pages.
    exact=0
    for k in range(29):
        q=t[np.flatnonzero(labels==k)[0]]
        # score() takes native masks; directly compute fixed normalized distances here.
        delta=np.abs(t.astype(np.int16)-q.astype(np.int16)).sum(axis=(1,2),dtype=np.int64)
        minima=np.array([delta[labels==v].min() for v in range(29)])
        assert np.argmin(minima)==k and minima[k]==0;exact+=1
    blank=score(np.zeros((115,40),dtype=bool),t,labels)
    assert not accepted(blank,f['distance_limit'],f['minimum_distinct_label_margin'])
    # Synthetic broad block corruption is deliberately outside the slender rune set.
    corrupt=score(np.ones((115,90),dtype=bool),t,labels)
    assert not accepted(corrupt,f['distance_limit'],f['minimum_distinct_label_margin'])
    result={'session':74,'scope':scope,'freeze_sha256':sha(ROOT/'glyph74_freeze.json'),
      'prediction_sha256':sha(ROOT/f'glyph74_{scope}_predictions.json'),
      'script_sha256':sha(Path(__file__)),'metrics':metrics,'failures':failures,
      'held_out_gate_passed':all(m['page_gate_passed'] for m in metrics) if scope=='held' else None,
      'target_recognition_performed':scope=='target',
      'controls':{'exact_template_label_fixtures':exact,'blank_abstention':True,'block_corruption_abstention':True},
      'no_new_plaintext':True,'master_sha256':sha(ROOT/'liber-primus__transcription--master.txt'),
      'limits':'Count-aligned rows are a condition on classification metrics, not automatic proof of each crop boundary. Unaligned rows fail the page gate and their labels are not counted as verified correct. Finite held-out success cannot certify future pages. Red glyphs and punctuation remain outside recognition scope.'}
    writejson('glyph74_results.json' if scope=='held' else 'glyph74_target_results.json',result)
    print(json.dumps({'metrics':[{k:v for k,v in m.items() if k!='rows'} for m in metrics],
                      'held_out_gate_passed':result['held_out_gate_passed'],'failures':len(failures),'controls':result['controls']},indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','read','evaluate']);p.add_argument('--scope',choices=['held','target'],default='held');a=p.parse_args()
    if a.action=='prepare':prepare()
    elif a.action=='read':read_images(a.scope)
    else:evaluate(a.scope)
