"""Build a cPanel source package; never include config, credentials or runtime data."""
import argparse,pathlib,shutil,json,hashlib,zipfile,tempfile,sys
p=argparse.ArgumentParser();p.add_argument('--with-studio',action='store_true');p.add_argument('--output',type=pathlib.Path,required=True);p.add_argument('--backend-only',action='store_true');args=p.parse_args();root=pathlib.Path(__file__).resolve().parents[1]
if args.with_studio == args.backend_only:sys.exit('Choose exactly one: --with-studio or --backend-only.')
if args.with_studio and not (root/'public/studio/index.php').is_file():sys.exit('Run tools/integrate-studio.py against the current Studio source first.')
if args.output.exists():sys.exit('Refusing to overwrite an existing archive.')
with tempfile.TemporaryDirectory(prefix='designpro-package-',dir='/private/tmp') as tmp:
 stage=pathlib.Path(tmp)/'designpro';stage.mkdir()
 for name in ['app','database','public','tools']:
  shutil.copytree(root/name,stage/name,ignore=shutil.ignore_patterns('__pycache__','*.pyc'))
 (stage/'private').mkdir()
 for name in ['.htaccess','README.md','config.example.php']:shutil.copy2(root/'private'/name,stage/'private'/name)
 for name in ['.htaccess','INSTALL.md','README.md','DEPLOYMENT-CHECKLIST.md','HANDOFF-WINDOWS.md']:shutil.copy2(root/name,stage/name)
 info=json.loads((stage/'public/assets/build-info.json').read_text())
 if args.backend_only:
  shutil.rmtree(stage/'public/studio',ignore_errors=True)
  if (stage/'app/studio-shell.html').exists():(stage/'app/studio-shell.html').unlink()
  info['studio_available']=False
 elif not info.get('studio_available'):sys.exit('Studio integration manifest missing.')
 (stage/'public/assets/build-info.json').write_text(json.dumps(info,indent=2)+'\n')
 entries=[]
 for f in sorted(stage.rglob('*')):
  if f.is_file():entries.append({'path':str(f.relative_to(stage)),'sha256':hashlib.sha256(f.read_bytes()).hexdigest()})
 manifest={'product':'Maker Sprout DesignPro PHP/MySQL','studio_available':info['studio_available'],'node_required':False,'production_credentials_included':False,'files':entries}
 (stage/'PACKAGE-MANIFEST.json').write_text(json.dumps(manifest,indent=2)+'\n')
 args.output.parent.mkdir(parents=True,exist_ok=True)
 with zipfile.ZipFile(args.output,'w',zipfile.ZIP_DEFLATED) as archive:
  for f in sorted(stage.rglob('*')):
   if f.is_file():archive.write(f,pathlib.Path('designpro')/f.relative_to(stage))
 with zipfile.ZipFile(args.output) as archive:
  assert archive.testzip() is None
  for entry in entries:assert hashlib.sha256(archive.read('designpro/'+entry['path'])).hexdigest()==entry['sha256']
 sha=hashlib.sha256(args.output.read_bytes()).hexdigest();pathlib.Path(str(args.output)+'.sha256').write_text(sha+'  '+args.output.name+'\n');print(json.dumps({'archive':str(args.output),'sha256':sha,'files':len(entries),'studio_available':info['studio_available']}))
