"""Compare existing local partitions against published UDE site/date metadata."""
import collections,csv,hashlib,json
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(x):
 s=x.strip().replace('\\','/').split('/')[-1].casefold();return s[:-5] if s.endswith('.tiff') else s[:-4] if s.endswith('.tif') else s
meta={r['slide_key']:r for r in csv.DictReader((O/'slide-metadata.csv').open())};s=json.loads(S.read_text());target={x['annotation_id']:x for x in s['sources']};full={}
with M.open(encoding='utf-8-sig',newline='') as f:
 for r in csv.DictReader(f):
  if r['annotation_id'] in target:full[r['annotation_id']]=r
assert set(target)==set(full);rows=[]
for ident,source in target.items():
 r=full[ident];site=meta.get(norm(r['image_filename']));rows.append({'annotation_id':ident,'partition':source['synthetic_partition'],'source_species':source['source_species'],'source_slide_group':source['canonical_group'],'image_filename':r['image_filename'],'metadata_match':'exact_normalized' if site else 'missing','site_code':site['site_code'] if site else None,'sampling_date':site['sampling_date'] if site else None,'year':site['year'] if site else None,'country':site['country'] if site else None,'basin':site['basin'] if site else None,'stream':site['stream'] if site else None,'treatment':site['treatment'] if site else None})
by_site=collections.defaultdict(lambda:collections.defaultdict(list));by_date=collections.defaultdict(lambda:collections.defaultdict(list));by_basin=collections.defaultdict(lambda:collections.defaultdict(list))
for r in rows:
 if r['site_code']:by_site[r['site_code'].strip().casefold()][r['partition']].append(r['annotation_id'])
 if r['site_code'] and r['sampling_date']:by_date[(r['site_code'].strip().casefold(),r['sampling_date'])][r['partition']].append(r['annotation_id'])
 if r['country'] and r['basin']:by_basin[(r['country'].strip().casefold(),r['basin'].strip().casefold())][r['partition']].append(r['annotation_id'])
def shared(groups):return [{'key':list(k) if isinstance(k,tuple) else k,'train_ids':v['train'],'validation_ids':v['validation']} for k,v in sorted(groups.items()) if v['train'] and v['validation']]
result={'format':'r112-ude-group-audit-v1','source_split_sha256':sha(S),'slide_metadata_sha256':sha(O/'slide-metadata.csv'),'parse_report_sha256':sha(O/'parse-report.json'),'script_sha256':sha(Path(__file__)),'counts':{'crops':len(rows),'exact_normalized_matches':sum(x['metadata_match']=='exact_normalized' for x in rows),'missing_slide_metadata':sum(x['metadata_match']=='missing' for x in rows),'missing_site_code':sum(not x['site_code'] for x in rows),'missing_sampling_date':sum(not x['sampling_date'] for x in rows),'shared_site_codes':len(shared(by_site)),'shared_site_dates':len(shared(by_date)),'shared_country_basins':len(shared(by_basin))},'shared_site_codes':shared(by_site),'shared_site_dates':shared(by_date),'shared_country_basins':shared(by_basin),'records':rows,'limitations':'Site/date grouping is conservative contextual evidence, not a guaranteed sample identifier. Shared site/date does not prove crops are the same specimen or sample, and different site/date strings do not prove independence. Unmatched or missing metadata must not be treated as unique independent groups. The analysis is retrospective and the comparison set is already consumed.'};(O/'group-audit.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result['counts'],indent=2))
