"""Integrate the current actual Studio source into a PHP-hosted snapshot, never edit canonical source."""
import argparse,pathlib,tempfile,shutil,subprocess,json,hashlib,os
p=argparse.ArgumentParser();p.add_argument('--source',type=pathlib.Path,required=True);p.add_argument('--node',default=shutil.which('node'));a=p.parse_args();root=pathlib.Path(__file__).resolve().parents[1];source=a.source.resolve();node=a.node
if not node:raise SystemExit('Node is needed locally to rebuild the existing UI bundle; no Node is required on cPanel.')
for n in ['index.html','app-source.js','app.js','cam-worker.js']:
 if not (source/n).is_file():raise SystemExit('Missing actual Studio source: '+n)
for f in source.rglob('*'):
 if f.is_symlink():raise SystemExit('Symlinked Studio source refused.')
target=root/'public/studio'
if target.exists():raise SystemExit('Refusing to overwrite existing Studio integration.')
with tempfile.TemporaryDirectory(prefix='designpro-studio-build-',dir='/private/tmp') as temporary:
 work=pathlib.Path(temporary);shutil.copytree(source,work/'web');(work/'tools').mkdir();builder=source.parent/'tools/build-ui.mjs';shutil.copy2(builder,work/'tools/build-ui.mjs')
 app=work/'web/app-source.js';code=app.read_text();signature='async function api(path,data,retry=true){';assert code.count(signature)==1
 code=code.replace(signature,signature+"throw Error('Local machine controls are unavailable on the hosted website. Use the website job queue.');")
 lines=code.splitlines();matches=[i for i,line in enumerate(lines) if line.startswith('const boothProjects=')];assert len(matches)==1 and lines[matches[0]].endswith('];');lines[matches[0]]='const boothProjects=[];';code='\n'.join(lines)+'\n'
 code=code.replace("$('demo').onclick=explorePhotoBoothFront;$('empty-demo').onclick=explorePhotoBoothFront;","$('demo').onclick=demo;$('empty-demo').onclick=demo;")
 startup="defaultStarter=true;$('booth-workpiece').value='0';$('booth-workpiece').onchange();";assert startup in code;code=code.replace(startup,'demo();')
 code=code.replace("'COMPANION OFFLINE'","'WEB DESIGN WORKSPACE'").replace("'Start the local companion to simulate'","'Browser simulation. Queue reviewed jobs through your website workspace.'")
 code=(root/'tools/studio-scope.js').read_text()+'\n'+code+'\n'+(root/'tools/studio-hosted.js').read_text();app.write_text(code)
 subprocess.run([node,str(work/'tools/build-ui.mjs')],check=True);subprocess.run([node,str(work/'tools/build-ui.mjs'),'--check'],check=True);shutil.copytree(work/'web',target)
 html=(target/'index.html').read_text().replace('Explore the photo-booth front','Explore a sample plate').replace('href="./"','href="../"',1).replace('<title>Maker Sprout Studio Pro</title>','<title>Design studio · Maker Sprout DesignPro</title>')
 html=html.replace('MAKER SPROUT <strong>STUDIO PRO</strong>','MAKER SPROUT <strong>DESIGNPRO</strong>').replace('CAM & MACHINE WORKSPACE','DESIGN & CNC PREPARATION')
 html=html.replace('<head>','<head><meta name="designpro-workspace" content="__DESIGNPRO_WORKSPACE__">',1).replace('</head>','<link rel="stylesheet" href="hosted.css"></head>',1)
 (root/'app/studio-shell.html').write_text(html);(target/'index.html').unlink()
 wrapper='''<?php
declare(strict_types=1);
ini_set('display_errors','0');
require dirname(__DIR__,2).'/app/api.php';
try {
 $config=\\DesignPro\\configuration();\\DesignPro\\secureRequest($config);\\DesignPro\\beginSession();
 $app=new \\DesignPro\\App(\\DesignPro\\connect($config),$config);[, $session]=$app->handle('GET','session');
 if(!$session['authenticated']) {header('Location: ../',true,302);exit;}
 session_write_close();
 header('Cache-Control: no-store');header('X-Content-Type-Options: nosniff');header('Referrer-Policy: same-origin');
 header("Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; worker-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'");
 echo str_replace('__DESIGNPRO_WORKSPACE__',htmlspecialchars($session['workspace']['id'],ENT_QUOTES,'UTF-8'),file_get_contents(dirname(__DIR__,2).'/app/studio-shell.html'));
} catch(Throwable) {http_response_code(503);echo 'Studio is unavailable. Return to the website workspace and check installation.';}
'''
 (target/'index.php').write_text(wrapper)
 (target/'hosted.css').write_text('.designpro-hosted-bar{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:12px 22px;background:#e9f0df;border-bottom:1px solid #c5d4c0;font-size:12px}.designpro-hosted-bar a{color:#125b4a;font-weight:700;text-decoration:none;margin-right:10px}.designpro-hosted-bar output{flex-basis:100%;color:#315d4c}#designpro-dialog{max-width:560px;width:calc(100% - 28px);border:1px solid #b6c9b8;border-radius:12px;padding:26px}#designpro-dialog input,#designpro-dialog select{display:block;width:100%;padding:10px;margin:8px 0 18px}#designpro-dialog h2{margin-bottom:14px}#designpro-dialog p{font-size:13px;line-height:1.6}#designpro-dialog::backdrop{background:#102b2470}')
 (target/'.htaccess').write_text('DirectoryIndex index.php\n<Files "index.html">\nRequire all denied\n</Files>\n')
 info=json.loads((root/'public/assets/build-info.json').read_text());info.update(studio_available=True,studio_integration='Authenticated actual Studio; workspace-scoped drafts; server save/open/queue; no local native controls',studio_source_manifest=[{'path':str(f.relative_to(source)),'sha256':hashlib.sha256(f.read_bytes()).hexdigest()} for f in sorted(source.rglob('*')) if f.is_file()]);(root/'public/assets/build-info.json').write_text(json.dumps(info,indent=2)+'\n')
 (root/'verification/STUDIO-INTEGRATION.json').write_text(json.dumps({'canonicalSource':str(source),'canonicalModified':False,'buildUiCheck':'PASS','camWorkerSha256':hashlib.sha256((target/'cam-worker.js').read_bytes()).hexdigest(),'originalCamWorkerSha256':hashlib.sha256((source/'cam-worker.js').read_bytes()).hexdigest(),'genericSample':True,'hostedSourcePatches':['disabled legacy local-native API','generic starter and unrelated prepared-project data removed','workspace storage scope','save/open/queue adapter'],'generatedBundlePatchedDirectly':False},indent=2)+'\n')
print('Actual Studio source integrated and rebuilt; original CAM worker preserved.')
