"""Copy the selected MIT-tagged marine-chain inputs to durable workspace storage."""
import hashlib,json,shutil
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'datasets/r81-chain';SRC=Path('/tmp/diatom-r52-pseudo');a=json.loads((R/'results/r81/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()
def copy(src,dst,expected):
 assert sha(src)==expected
 if dst.exists():
  if sha(dst)!=expected:raise ValueError('Existing file differs: '+str(dst))
 else:
  temp=dst.with_suffix(dst.suffix+'.part');shutil.copyfile(src,temp);assert sha(temp)==expected;temp.replace(dst)
 items.append({'temporary_path':str(src),'local_path':str(dst.relative_to(R)),'sha256':expected})
for row in a['selected']:copy(Path(row['path']),O/'images'/row['filename'],row['sha256'])
copy(SRC/'instances_default.json',O/'instances_default.json',a['annotation_sha256'])
for name in ('train','val','test'):copy(SRC/(name+'.txt'),O/(name+'.txt'),a['split_sha256'][name])
(O/'manifest.json').write_text(json.dumps({'format':'r81-source-mirror-v1','dataset_revision':'27bae108cff829cf0ee26e93a8d063d04d1ceb17','dataset':'https://huggingface.co/datasets/patcdaniel/pseudo-nitzschia-cell-segmentation','license':'MIT tag in publisher dataset metadata; check upstream terms for further use','items':items},indent=2)+'\n');print('Verified and retained',len(items),'source files.')
