"""Copy R80's selected licensed source files into durable local project storage."""
import hashlib,json,shutil
from pathlib import Path
R=Path(__file__).resolve().parents[1];out=R/'datasets/r80-gunduz';audit=json.loads((R/'results/r80/source-audit.json').read_text());items=[]
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()
for row in audit['targets']:
 for kind,dest in [('image','images'),('mask','masks'),('xml','xml')]:
  src=Path(row[kind+'_path']);expected=row[kind+'_sha256'];target=out/dest/src.name;assert sha(src)==expected
  if target.exists():
   if sha(target)!=expected:raise ValueError('Existing target differs: '+str(target))
  else:
   temp=target.with_suffix(target.suffix+'.part');shutil.copyfile(src,temp)
   if sha(temp)!=expected:raise ValueError('Copy verification failed')
   temp.replace(target)
  items.append({'kind':kind,'source_temporary_path':str(src),'local_path':str(target.relative_to(R)),'sha256':expected})
(out/'manifest.json').write_text(json.dumps({'format':'r80-source-mirror-v1','source_audit_sha256':sha(R/'results/r80/source-audit.json'),'items':items,'license':'CC BY-NC-SA 4.0; source: Hüseyin Gündüz, Diatom Dataset, https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset'},indent=2)+'\n');print('Preserved and SHA-256 verified',len(items),'source images/masks/XML files.')
