"""Retrospectively locate grid, mask generation, filtering and ranking losses."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import numpy as np
from r112_grouped_baseline import iou_matrix,match
R=Path(__file__).resolve().parents[1];B=R/'results/r112/grouped-baseline';O=R/'results/r112/grouped-prompt-diagnostic';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
p=json.loads((O/'protocol.json').read_text());assert not (O/'results.json').exists()
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
baseline=json.loads((B/'results.json').read_text());rows=[];start=time.monotonic()
for i,row in enumerate(baseline['records']):
 f=B/row['archive'];assert sha(f)==row['archive_sha256'];z=np.load(f);shape=tuple(z['mask_shape']);cands=np.unpackbits(z['mask_bits'])[:np.prod(shape)].reshape(shape).astype(bool);rs=tuple(z['reference_shape']);refs=np.unpackbits(z['reference_bits'])[:np.prod(rs)].reshape(rs).astype(bool);points=z['points'];idx=np.flatnonzero(refs.sum(axis=(1,2))>=50);iou=iou_matrix(refs,cands[:256]);d={}
 for n in (64,256):
  grid=points[:n];covered=refs[:,grid[:,1],grid[:,0]].any(axis=1);raw=list(range(n));eligible=[j for j in raw if z['sam_eligible'][j]];kept=row['policies'][f'sam{n}']['ranking'];stages={'raw_oracle':raw,'eligible_oracle':eligible,'kept_oracle':kept,'top30':kept[:30]};stage={}
  for name,cs in stages.items():
   assignments=match(iou,idx,cs,.5);stage[name]={'matched':len(assignments),'assignments':assignments}
  assert stage['top30']['matched']==row['policies'][f'sam{n}']['budgets']['30']['matches']['main_0.5']['matched'] and stage['kept_oracle']['matched']==row['policies'][f'sam{n}']['budgets']['all']['matches']['main_0.5']['matched'];d[str(n)]={'grid_covers':int(covered[idx].sum()),'grid_covered_indices':idx[covered[idx]].tolist(),'raw_candidate_exists_for_support':int((iou[idx,:n]>=.5).any(axis=1).sum()),'stages':stage,'references':len(idx)}
 rows.append({'scene_id':row['scene_id'],'archive_sha256':row['archive_sha256'],'policies':d})
 if (i+1)%12==0:print(i+1,'/',len(baseline['records']),'elapsed',round(time.monotonic()-start,1),flush=True)
summary={}
for n in ('64','256'):
 summary[n]={'references':sum(x['policies'][n]['references'] for x in rows),'grid_covers':sum(x['policies'][n]['grid_covers'] for x in rows),'raw_candidate_exists_for_support':sum(x['policies'][n]['raw_candidate_exists_for_support'] for x in rows),'stages':{k:sum(x['policies'][n]['stages'][k]['matched'] for x in rows) for k in ('raw_oracle','eligible_oracle','kept_oracle','top30')}}
r={'format':p['format'],'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(Path(__file__)),'summary':summary,'warning':p['limitations'],'records':rows};(O/'results.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(summary,indent=2))
