"""Search indexed local result metadata/artifact names for candidate-location IDs."""
import csv,hashlib,json,re,subprocess,tempfile
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/ude-sampling-metadata';L=O/'exposure-ledger.csv';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();ids={r['annotation_id'] for r in csv.DictReader(L.open()) if r['exposure_status']=='candidate_unseen_location'};assert len(ids)==906
with tempfile.TemporaryDirectory(dir='/tmp',prefix='r112-id-audit-') as tmp:
 f=Path(tmp)/'ids.txt';f.write_text('\n'.join(sorted(ids))+'\n');q=subprocess.run(['rg','-l','-F','-f',str(f),'results','--glob','*.json','--glob','!r112/ude-sampling-metadata/**'],cwd=R,capture_output=True,text=True);assert q.returncode in (0,1),q.stderr;files=q.stdout.splitlines()
exact=[]
def visit(x,path,file):
 if isinstance(x,dict):
  for k,v in x.items():visit(v,path+'/'+str(k),file)
 elif isinstance(x,list):
  for i,v in enumerate(x):visit(v,path+'/'+str(i),file)
 elif isinstance(x,(str,int)):
  s=str(x);found=({s} if s in ids else set())|({n for n in re.findall(r'(?<![\da-fA-F])\d{8}(?![\da-fA-F])',s) if n in ids})
  for ident in found:exact.append({'file':file,'json_path':path,'annotation_id':ident})
for f in files:
 try:visit(json.loads((R/f).read_text()),'',f)
 except (ValueError,UnicodeError,OSError) as ex:raise RuntimeError('Could not audit '+f) from ex
q=subprocess.run(['rg','--files','results','datasets','-g','*.png','-g','*.jpg','-g','*.tif','-g','*.tiff','-g','*.npz'],cwd=R,capture_output=True,text=True);assert q.returncode in (0,1),q.stderr;paths=[]
for p in q.stdout.splitlines():
 for ident in re.findall(r'(?<!\d)\d{8}(?!\d)',p):
  if ident in ids:paths.append({'path':p,'annotation_id':ident})
result={'format':'r112-candidate-exposure-scan-v1','ledger_sha256':sha(L),'script_sha256':sha(Path(__file__)),'candidate_annotation_ids':len(ids),'json_files_with_raw_substring_hits':len(files),'json_exact_id_hits':exact,'image_or_archive_paths_with_id_hits':paths,'limitations':'Searches existing results JSON values and image/archive filenames for exact eight-digit annotation IDs. It cannot detect prior display under different IDs, source filenames without annotation IDs, renamed or cached images, other output formats, outside-workspace use, model pretraining or biological sample overlap. A zero result is not proof of no prior exposure.'};(O/'candidate-exposure-scan.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({k:result[k] for k in ('candidate_annotation_ids','json_files_with_raw_substring_hits','json_exact_id_hits','image_or_archive_paths_with_id_hits')},indent=2))
