"""Build conservative site-connectivity groups from published UDE slide metadata."""
import collections,csv,hashlib,json,math
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/ude-sampling-metadata';M=Path('/tmp/ude-metadata.csv');S=R/'results/r112/grouped-synthetic/split.json';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def norm_slide(x):
 s=x.strip().replace('\\','/').split('/')[-1].casefold();return s[:-5] if s.endswith('.tiff') else s[:-4] if s.endswith('.tif') else s
def site(x):
 s=' '.join(x.split()).casefold();return None if s in ('','none','na','n/a','unknown','-') else s
def coordinate(a,b):
 try:lat,lon=float(a),float(b)
 except (TypeError,ValueError):return None
 if not (math.isfinite(lat) and math.isfinite(lon) and -90<=lat<=90 and -180<=lon<=180) or (lat==0 and lon==0):return None
 return (round(lat,6),round(lon,6))
rows=list(csv.DictReader((O/'slide-metadata.csv').open()));n=len(rows);parent=list(range(n))
def find(x):
 while parent[x]!=x:parent[x]=parent[parent[x]];x=parent[x]
 return x
def merge(a,b):
 a,b=find(a),find(b)
 if a!=b:parent[max(a,b)]=min(a,b)
seen_site={};seen_coord={};unresolved=[]
for i,r in enumerate(rows):
 keys=[('site',site(r['site_code']),seen_site),('coordinate',coordinate(r['latitude'],r['longitude']),seen_coord)];valid=False
 for _,k,lookup in keys:
  if k is None:continue
  valid=True
  if k in lookup:merge(i,lookup[k])
  else:lookup[k]=i
 if not valid:unresolved.append(r['slide_key'])
components=collections.defaultdict(list)
for i,r in enumerate(rows):components[find(i)].append(r)
output=[];lookup={}
for _,members in sorted(components.items(),key=lambda kv:min(x['slide_key'] for x in kv[1])):
 slides=sorted(r['slide_key'] for r in members);gid='site-'+hashlib.sha256('\n'.join(slides).encode()).hexdigest()[:16];entry={'component_id':gid,'slide_keys':slides,'site_codes':sorted({r['site_code'] for r in members if site(r['site_code'])}),'coordinates':sorted({str(coordinate(r['latitude'],r['longitude'])) for r in members if coordinate(r['latitude'],r['longitude'])}),'countries':sorted({r['country'] for r in members if r['country']}),'basins':sorted({r['basin'] for r in members if r['basin']}),'sampling_dates':sorted({r['sampling_date'] for r in members if r['sampling_date']})};output.append(entry)
 for key in slides:lookup[key]=gid
assert len(lookup)==n and len(set(lookup))==n;by_group=collections.Counter();missing=collections.Counter();ids={x['annotation_id']:x for x in json.loads(S.read_text())['sources']};related=collections.defaultdict(lambda:collections.defaultdict(list));found=set()
with M.open(encoding='utf-8-sig',newline='') as f:
 for r in csv.DictReader(f):
  key=norm_slide(r['image_filename']);gid=lookup.get(key)
  if gid is None:missing[key]+=1
  else:by_group[gid]+=1
  if r['annotation_id'] in ids:
   found.add(r['annotation_id']);part=ids[r['annotation_id']]['synthetic_partition']
   if gid is not None:related[gid][part].append(r['annotation_id'])
assert found==set(ids);shared=[{'component_id':g,'train_ids':v['train'],'validation_ids':v['validation']} for g,v in sorted(related.items()) if v['train'] and v['validation']];out={'format':'r112-ude-site-components-v1','slide_metadata_sha256':sha(O/'slide-metadata.csv'),'parse_report_sha256':sha(O/'parse-report.json'),'source_metadata_sha256':sha(M),'existing_local_split_sha256':sha(S),'script_sha256':sha(Path(__file__)),'method':'Union all published slide records that share normalized nonempty site code OR identical latitude/longitude rounded to six decimal places; connection is transitive. Missing site and valid coordinates is unresolved, never inferred unique. This conservative geographic grouping is for split design, not a biological sample identity.','component_count':len(output),'unresolved_published_slide_keys':unresolved,'unmatched_ude_slide_keys_and_crop_counts':dict(missing),'grouped_crop_count':sum(by_group.values()),'shared_components_in_existing_local_split':shared,'components':[dict(x,crop_count=by_group[x['component_id']]) for x in output],'limitations':'Coarse or inaccurate coordinates may overmerge unrelated sites; inconsistent codes or positions may miss related collections; proximity, watershed, seasonal dependence and sample relationships remain unproven. No classification of a component as an independently sampled biological entity is justified solely by this grouping.'};(O/'site-components.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps({'slide_rows':n,'site_components':len(output),'unresolved_published_slides':len(unresolved),'grouped_crops':sum(by_group.values()),'unmatched_crops':sum(missing.values()),'existing_split_shared_site_components':len(shared),'component_size_max_slides':max(len(x['slide_keys']) for x in output)},indent=2))
