"""Compare fixed R38 and R41 specimen crops for obvious perceptual similarity."""
import json,hashlib
from pathlib import Path
import cv2,numpy as np
from PIL import Image
import r38_synthetic_crossings as r38
import r41_consensus_fresh_sources as r41
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r76'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def hash_crop(crop,mask):
 # Masked-out surrounding pixels use median observed foreground intensity;
 # square resize intentionally permits aspect distortion for coarse screening.
 gray=cv2.cvtColor(crop,cv2.COLOR_RGB2GRAY);gray=np.where(mask,gray,int(np.median(gray[mask]))).astype('uint8');x=cv2.resize(gray,(32,32),interpolation=cv2.INTER_AREA).astype('float32');d=cv2.dct(x)[:8,:8].ravel()[1:];return d>np.median(d)
def hash_image(path):
 x=np.asarray(Image.open(path).convert('L').resize((32,32),Image.Resampling.LANCZOS),dtype='float32');d=cv2.dct(x)[:8,:8].ravel()[1:];return d>np.median(d)
def main():
 r38select=json.loads(r38.SELECTION.read_text())['selection'];r41select=json.loads(r41.SOURCE.read_text())['selection'];a=[r38.extract(e,i) for i,e in enumerate(r38select,1)];b=[r41.extract21(r41select[i-1],i) for i in r41.INDICES];p38=json.loads((ROOT/'results/r38/protocol.json').read_text());p41=json.loads((ROOT/'results/r41/protocol.json').read_text());assert [x[2] for x in a]==p38['source_objects'] and [x[2] for x in b]==p41['source_objects'];cross=[]
 for i,(crop,mask,meta) in enumerate(a,1):
  for j,(other,om,metadata) in enumerate(b,1):
   assert meta['image_sha256']!=metadata['image_sha256'];base=hash_crop(crop,mask);variants=[]
   for flip in (False,True):
    for k in range(4):
     img=np.rot90(np.fliplr(other) if flip else other,k).copy();ms=np.rot90(np.fliplr(om) if flip else om,k).copy();variants.append(int(np.count_nonzero(base!=hash_crop(img,ms))))
   whole=int(np.count_nonzero(hash_image(Path('/tmp/diatom-mask-images')/f'{i:02d}.jpg')!=hash_image(Path('/tmp/diatom-adaptation')/f'{r41.INDICES[j-1]:02d}.jpg')))
   cross.append({'r38_index':i,'r41_index':r41.INDICES[j-1],'exact_sha256_match':False,'whole_image_dct_hash_distance':whole,'crop_min_8_orientation_dct_hash_distance':min(variants)})
 report={'format':'r76-source-similarity-audit-v1','r38_objects':[x[2] for x in a],'r41_objects':[x[2] for x in b],'comparisons':cross,'threshold_note':'A coarse 63-bit DCT hash (0 is identical) is a screening aid only; no universal threshold or guarantee against duplicate, related, rotated, cropped, differently focused, or overlapping specimens. Aspect-ratio distortion and foreground masking can create misleading distances.','scripts':[{'path':str(Path(__file__)),'sha256':sha(Path(__file__))},{'path':str(Path(r38.__file__)),'sha256':sha(Path(r38.__file__))},{'path':str(Path(r41.__file__)),'sha256':sha(Path(r41.__file__))}]};(OUT/'source-audit.json').write_text(json.dumps(report,indent=2)+'\n');print('Verified source and annotation hashes, 36 cross-group comparisons; minimum whole/crop distances:',min(x['whole_image_dct_hash_distance'] for x in cross),min(x['crop_min_8_orientation_dct_hash_distance'] for x in cross));print('Crop pairs distance <= 8:',[(x['r38_index'],x['r41_index'],x['crop_min_8_orientation_dct_hash_distance']) for x in cross if x['crop_min_8_orientation_dct_hash_distance']<=8])
if __name__=='__main__':main()
