"""Restore missing R80 temporary source paths from the verified local mirror."""
import hashlib,json,shutil
from pathlib import Path
R=Path(__file__).resolve().parents[1];M=R/'datasets/r80-gunduz/manifest.json'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
 return h.hexdigest()
def main():
 manifest=json.loads(M.read_text());restored=0
 for x in manifest['items']:
  src=R/x['local_path'];target=Path(x['source_temporary_path']);expected=x['sha256']
  if not target.resolve().is_relative_to(Path('/tmp')):raise ValueError('Target must be inside /tmp')
  if sha(src)!=expected:raise ValueError('Mirror differs: '+str(src))
  if target.exists():
   if sha(target)!=expected:raise ValueError('Existing temporary source differs: '+str(target))
   continue
  target.parent.mkdir(parents=True,exist_ok=True);temp=target.with_suffix(target.suffix+'.restore-part');shutil.copyfile(src,temp)
  if sha(temp)!=expected:raise ValueError('Restore verification failed: '+str(target))
  temp.replace(target);restored+=1
 print('Verified',len(manifest['items']),'mirror files; restored',restored,'missing temporary files.')
if __name__=='__main__':main()
