"""Prepare bounded-size static assets; preserve the original complete ZIP privately."""
import argparse
import json
from pathlib import Path
import shutil

from download_evidence import digest
from provider import dump


def split(directory,limit=20*1024*1024):
 directory=Path(directory);index=json.loads((directory/'experiment-index.json').read_text(encoding='utf-8'))
 for bundle in index['bundles']:
  source=directory/bundle['filename'];files=[]
  if source.stat().st_size>limit:
   with source.open('rb') as f:
    part=0
    while chunk:=f.read(limit):
     part+=1;target=directory/(source.name+f'.part{part:03}');target.write_bytes(chunk);files.append({'filename':target.name,'bytes':len(chunk),'sha256':digest(target)})
  else:files=[{'filename':source.name,'bytes':source.stat().st_size,'sha256':digest(source)}]
  bundle['download_files']=files;bundle['assembly_required']=len(files)>1
 dump(directory/'experiment-index.json',index);dump(directory/'DOWNLOADS.json',{'note':'Multipart files concatenate in the listed order to the original ZIP. The helper verifies both part and whole-archive hashes; it does not run models or extract files.','bundles':index['bundles']})
 shutil.copy2(Path(__file__).with_name('download_evidence.py'),directory/'download_evidence.py')
 print(json.dumps(index['bundles'],indent=2))


if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('directory');args=ap.parse_args();split(args.directory)
