"""Development-only partial-view stress test on public UDE validation crops."""
import hashlib,html,json
from pathlib import Path
import numpy as np
import torch
from PIL import Image,ImageOps,ImageDraw
from torchvision.models import resnet18
from run_field import embedding

ROOT=Path(__file__).resolve().parents[1];DATA=ROOT/'results/pilot/ude-adaptation-within-genus';OUT=ROOT/'results/l28';ENCODER=Path('/tmp/resnet18-f37072fd.pth')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()

def main():
    selection=json.loads((DATA/'selection.json').read_text());validation=json.loads((DATA/'centroid-pilot/validation.json').read_text());report=json.loads((DATA/'download-report.json').read_text())
    if sha(DATA/'selection.json')!=report['selection_sha256'] or validation['selection_sha256']!=report['selection_sha256'] or sha(ENCODER)!=validation['generic_weights_sha256']:raise ValueError('Provenance mismatch')
    rows=[r for r in selection['rows'] if r['split']=='validation'];byid={r['annotation_id']:r for r in report['images']}
    if len(rows)!=16:raise ValueError('Unexpected validation composition')
    for r in rows:
        if sha(DATA/r['local_file'])!=byid[r['annotation_id']]['sha256']:raise ValueError('Image integrity mismatch')
    with np.load(DATA/'centroid-pilot/prototypes.npz') as f:centroids=f['generic'].copy()
    model=resnet18(weights=None);model.load_state_dict(torch.load(ENCODER,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();torch.set_num_threads(4);OUT.mkdir(parents=True,exist_ok=True)
    results=[]
    for row in rows:
        with Image.open(DATA/row['local_file']) as f:image=f.convert('RGB')
        w,h=image.size
        # Crop the first half along the rectangular image's long axis. This is
        # a reproducible geometric stress test, not a real occlusion model.
        box=(0,0,w//2,h) if w>=h else (0,0,w,h//2)
        partial=image.crop(box);rec={'annotation_id':row['annotation_id'],'slide':row['source_slide'],'species':row['species'],'genus':row['genus'],'views':{}}
        for name,img in [('full',image),('half',partial)]:
            vector=embedding(model,img);scores=centroids@vector;pred=validation['labels'][int(np.argmax(scores))]
            rec['views'][name]={'species':pred,'genus':pred.split()[0]}
        panel=Image.new('RGB',(440,190),'white');draw=ImageDraw.Draw(panel)
        for x,(name,img) in enumerate([('full',image),('half',partial)]):
            thumb=ImageOps.contain(img,(210,150));panel.paste(thumb,(x*220+(210-thumb.width)//2,25+(150-thumb.height)//2));draw.text((x*220+5,5),name,fill='black')
        panel.save(OUT/(row['annotation_id']+'.jpg'),quality=88);results.append(rec)
    metrics={name:{rank:sum(r[rank]==r['views'][name][rank] for r in results) for rank in ('genus','species')} for name in ('full','half')}
    if metrics['full']['species']!=validation['metrics']['generic']['top1_species_exact']:raise ValueError('Full-view score differs from prior validation')
    payload={'format':'l28-partial-public-v1','selection_sha256':sha(DATA/'selection.json'),'prototype_sha256':sha(DATA/'centroid-pilot/prototypes.npz'),
             'encoder_sha256':sha(ENCODER),'n':len(results),'source_slides':len({x['slide'] for x in results}),'metrics':metrics,'records':results,
             'warning':'Geometric half-crops of previously inspected public validation images, not real partial valves, overlaps, automatic detection, or independent held-out performance.'}
    (OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
    cards=[]
    for r in results:
        cards.append('<article><img src="'+html.escape(r['annotation_id'])+'.jpg" alt="Full crop and geometric half crop"><p>Dataset: '+html.escape(r['species'])+'<br>Full: '+html.escape(r['views']['full']['species'])+'<br>Half: '+html.escape(r['views']['half']['species'])+'</p></article>')
    page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Partial-view public stress test</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1150px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:12px}article{background:white;border:1px solid #ccd9d1;padding:12px}img{width:100%;max-width:440px}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/L28.md">Research note</a></nav><h1>Partial-view public stress test</h1><p class="notice">These are geometric half-crops from previously examined public validation images, not real partial diatoms or overlaps. The classifier must select one of four known species. This is not held-out or Academy performance.</p><p>On {N} images from {S} source-slide names: full views {GENUS1}/{N} genus and {SPEC1}/{N} species; half views {GENUS2}/{N} genus and {SPEC2}/{N} species. <a href="results.json">Raw results</a></p><div class="grid">{CARDS}</div></main></html>'''
    for key,value in [('GENUS1',metrics['full']['genus']),('SPEC1',metrics['full']['species']),('GENUS2',metrics['half']['genus']),('SPEC2',metrics['half']['species']),('N',len(results)),('S',payload['source_slides']),('CARDS',''.join(cards))]:page=page.replace('{'+key+'}',str(value))
    (OUT/'index.html').write_text(page);print(json.dumps(metrics))

if __name__=='__main__':main()
