"""Observe proposal checkpoints and verify completed mask artifacts."""
import datetime,json,os,subprocess,sys,time
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup/mask-hypotheses';P=O/'progress.json';STATUS=O/'watch-status.json';LOG=O/'verify-run.log';PY='/tmp/diatom-research-venv/bin/python'
def status(phase,**kw):
 tmp=STATUS.with_suffix('.json.tmp');tmp.write_text(json.dumps({'phase':phase,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Last checkpoint; status file alone does not establish process liveness.',**kw},indent=2)+'\n');tmp.replace(STATUS)
def main():
 end=time.monotonic()+4*60*60;last=None;last_change=time.monotonic();status('watching_proposals')
 while time.monotonic()<end:
  if P.exists():
   x=json.loads(P.read_text());phase=x.get('phase');marker=(phase,x.get('processed_this_run'),x.get('completed'))
   if marker!=last:last_change=time.monotonic();last=marker
   if phase in ('completed','completed_with_missing'):
    status('verifying_proposals',proposal_phase=phase);env={**os.environ,'PYTHONPATH':str(R)+':'+str(R/'research'),'OMP_NUM_THREADS':'1','OPENBLAS_NUM_THREADS':'1','YOLO_CONFIG_DIR':'/tmp/diatom-yolo-config'}
    with LOG.open('w') as log:p=subprocess.run([PY,'-u',str(R/'research/r112_scaleup_masks_verify.py')],cwd=R,env=env,stdout=log,stderr=subprocess.STDOUT)
    if p.returncode:status('verification_failed',exit_code=p.returncode);return p.returncode
    result=json.loads((O/'verify.json').read_text());status('verified_complete' if not result['missing_ids'] else 'verified_with_missing',verified_records=result['verified_records'],missing_count=len(result['missing_ids']));return 0
  if time.monotonic()-last_change>=900:status('no_checkpoint_change_15_minutes');return 1
  time.sleep(15)
 status('watch_timeout');return 1
if __name__=='__main__':sys.exit(main())
