"""Flag a few highly repetitive image patterns; not a registration guarantee."""
import numpy as np

def _correlation(a,b):
 a=a.astype('float32');b=b.astype('float32');a=a-a.mean();b=b-b.mean();den=float(np.sqrt(np.sum(a*a,dtype='float64')*np.sum(b*b,dtype='float64')))
 return float(np.sum(a*b,dtype='float64')/den) if den>0 else None

def periodic_ambiguity(reference,target,periods=(4,8,16,32),threshold=.995):
 """Check axis-aligned repeated texture at a small fixed set of pixel lags.

 High similarity in both images indicates ambiguity, not a solved alignment.
 Other periods, rotations, and approximate repeats may go undetected.
 """
 if not isinstance(reference,np.ndarray) or not isinstance(target,np.ndarray) or reference.ndim!=2 or reference.shape!=target.shape or min(reference.shape)<64:raise ValueError('Expected equal-sized images of at least 64 pixels per side')
 if not np.issubdtype(reference.dtype,np.number) or not np.issubdtype(target.dtype,np.number) or not np.isfinite(reference).all() or not np.isfinite(target).all():raise ValueError('Expected finite numeric inputs')
 if np.ptp(reference)==0 or np.ptp(target)==0:return {'status':'unidentifiable_constant','flags':[]}
 if not 0<threshold<=1 or not periods or any(type(x) is not int or not 0<x<min(reference.shape) for x in periods):raise ValueError('Invalid parameters')
 flags=[]
 for n in periods:
  for axis in ('x','y'):
   if axis=='x':a,b=reference[:,:-n],reference[:,n:];c,d=target[:,:-n],target[:,n:]
   else:a,b=reference[:-n,:],reference[n:,:];c,d=target[:-n,:],target[n:,:]
   ra,rb=_correlation(a,b),_correlation(c,d)
   if ra is not None and rb is not None and ra>=threshold and rb>=threshold:flags.append({'axis':axis,'lag_px':n,'reference_correlation':ra,'target_correlation':rb})
 return {'status':'ambiguous_periodic' if flags else 'no_flag','flags':flags}
