"""Check the verified UDE archive against prior development crops and guards."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_development_archive import UDEDevelopmentArchive,DEFAULT_ARCHIVE,DEFAULT_LEDGER,DEFAULT_REPORT,DEFAULT_VERIFICATION,source_name_flags
R=Path(__file__).resolve().parents[1];O=R/'results/r112/ude-sampling-metadata';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();spec=[('species-depth','development-assets.json'),('diversity-fetch','assets.json'),('breadth-depth','development-assets.json'),('new-taxa','development-assets.json')];checks=[];blocked={}
with UDEDevelopmentArchive() as dataset:
 for dirname,fn in spec:
  root=R/'results/r112'/dirname;records=json.loads((root/fn).read_text())['records'];chosen=next(r for r in records if dataset.rows[r['annotation_id']]['exposure_status']=='prior_development' and not source_name_flags(r['source_genus'],r['source_species']));x=dataset.read(chosen['annotation_id'],require_plain_species=True);local=root/chosen['source_crop'];assert sha(local)==chosen['source_sha256']==x['archive_member_sha256'] and np.array_equal(np.asarray(Image.open(local).convert('L')),np.asarray(x['image']));checks.append({'pool':dirname,'annotation_id':chosen['annotation_id'],'archive_member_sha256':x['archive_member_sha256'],'pixels_equal_prior_local_crop':True})
 for status in ('legacy_reserved','legacy_reserved_conflict','candidate_unseen_location','unmatched_slide_quarantine'):
  ident=next(k for k,v in dataset.rows.items() if v['exposure_status']==status)
  try:dataset.read(ident)
  except PermissionError:blocked[status]=True
  else:raise AssertionError('Protected exposure status was readable')
result={'format':'r112-ude-archive-integration-v1','archive_sha256':sha(DEFAULT_ARCHIVE),'ledger_sha256':sha(DEFAULT_LEDGER),'exposure_report_sha256':sha(DEFAULT_REPORT),'archive_verification_sha256':sha(DEFAULT_VERIFICATION),'script_sha256':sha(Path(__file__)),'development_examples':checks,'protected_statuses_rejected':blocked,'limitations':'Only four known development images were compared. Archive checksum and per-member CRCs establish file integrity, not biological identity, masks, sample independence or model performance.'};(O/'archive-integration.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
