"""Wait for verified archive, then extract and check the frozen development pool."""
import datetime,json,os,subprocess,sys,time
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup';A=R/'datasets/r112-ude-full/ude-2024.zip';P=R/'results/r112/ude-sampling-metadata/download-progress.json';LOG=O/'worker.log';STATUS=O/'worker-status.json';PY='/tmp/diatom-research-venv/bin/python'
def status(phase,**fields):
 tmp=STATUS.with_suffix('.json.tmp');tmp.write_text(json.dumps({'phase':phase,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'Last saved checkpoint; this status file alone is not a live process indicator.',**fields},indent=2)+'\n');tmp.replace(STATUS)
def main():
 deadline=time.monotonic()+4*60*60;status('waiting_for_verified_archive')
 while time.monotonic()<deadline:
  if A.exists() and (R/'results/r112/ude-sampling-metadata/archive-verification.json').exists():break
  if P.exists():
   state=json.loads(P.read_text())
   if state.get('phase') in ('checksum_mismatch','unexpected_size','duplicate_archive_members','no_growth_10_minutes','watch_timeout'):
    status('waiting_stopped',reason='Archive watcher reported '+state['phase']);return 1
  time.sleep(10)
 else:status('waiting_timeout');return 1
 env={**os.environ,'PYTHONPATH':str(R),'OMP_NUM_THREADS':'2','OPENBLAS_NUM_THREADS':'2'}
 with LOG.open('a') as out:
  for phase,script in [('archive_integration','research/r112_ude_archive_integration.py'),('extracting','research/r112_scaleup_extract.py'),('verifying','research/r112_scaleup_verify.py')]:
   if phase=='extracting' and (O/'assets.json').exists():continue
   status(phase);result=subprocess.run([PY,'-u',str(R/script)],cwd=R,env=env,stdout=out,stderr=subprocess.STDOUT)
   if result.returncode:status('failed',failed_phase=phase,exit_code=result.returncode,log=str(LOG.relative_to(R)));return result.returncode
 status('complete',assets=str((O/'assets.json').relative_to(R)),verification=str((O/'verify.json').relative_to(R)));return 0
if __name__=='__main__':sys.exit(main())
