"""Observe an existing public UDE download; verify its complete archive before use."""
import datetime,hashlib,json,os,time,zipfile
from pathlib import Path
R=Path(__file__).resolve().parents[1];D=R/'datasets/r112-ude-full';O=R/'results/r112/ude-sampling-metadata';PART=D/'ude-2024.zip.partial';FINAL=D/'ude-2024.zip';STATUS=O/'download-progress.json';SIZE=2084450931;EXPECTED='4b46497fb17693aa361e59a0fc91c8bf'
def save(phase,size,**extra):
 data={'format':'r112-ude-download-progress-v1','phase':phase,'bytes_observed':size,'expected_bytes':SIZE,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'source':'https://zenodo.org/records/10410655','note':'Observed file size is not proof that a process is live; partial data are never used as a complete archive.',**extra};tmp=STATUS.with_suffix('.json.tmp');tmp.write_text(json.dumps(data,indent=2)+'\n');tmp.replace(STATUS)
def main():
 previous=-1;changed=time.monotonic();deadline=changed+4*60*60
 while time.monotonic()<deadline:
  if FINAL.exists():save('verified_archive_exists',FINAL.stat().st_size,note='A verified archive path exists; consult archive-verification.json for its verification record.');return
  size=PART.stat().st_size if PART.exists() else 0
  if size>SIZE:save('unexpected_size',size);raise ValueError('Archive larger than expected; retained for inspection')
  if size==SIZE:
   save('verifying_integrity',size);md5=hashlib.md5();sha=hashlib.sha256()
   with PART.open('rb') as f:
    for chunk in iter(lambda:f.read(1024*1024),b''):md5.update(chunk);sha.update(chunk)
   if md5.hexdigest()!=EXPECTED:save('checksum_mismatch',size,observed_md5=md5.hexdigest());raise ValueError('Public archive checksum mismatch; retained partial file')
   with zipfile.ZipFile(PART) as z:
    info=z.infolist();members=len(info);dupes=members-len({x.filename for x in info})
   if dupes:save('duplicate_archive_members',size,duplicate_names=dupes);raise ValueError('Duplicate member names need investigation')
   record={'format':'r112-ude-full-archive-v1','source':'https://zenodo.org/records/10410655','published_md5':EXPECTED,'computed_md5':md5.hexdigest(),'computed_sha256':sha.hexdigest(),'bytes':size,'zip_members':members,'duplicate_member_names':dupes,'limitations':'Global archive checksum and ZIP central directory checked; individual members must still be read and CRC-checked when used. Archive includes unselected candidate and legacy test material; do not treat all images as training data.'};(O/'archive-verification.json').write_text(json.dumps(record,indent=2)+'\n');PART.replace(FINAL);save('verified',size,archive='datasets/r112-ude-full/ude-2024.zip',sha256=sha.hexdigest());print('archive verified',size,'bytes',flush=True);return
  if size!=previous:changed=time.monotonic();phase='observed_growth' if previous>=0 else 'observing'
  else:phase='no_recent_growth'
  save(phase,size);previous=size
  if time.monotonic()-changed>=600:save('no_growth_10_minutes',size);print('Watcher ended after no file growth; process state not determined.',flush=True);return
  time.sleep(15)
 save('watch_timeout',PART.stat().st_size if PART.exists() else 0);print('Watcher reached its four-hour limit.',flush=True)
if __name__=='__main__':main()
