"""CSP-compatible Ultra3D embind glue modification, 2026-11-11.
LGPL-2.1-or-later. Usage: python patch-embind-static.py ORIGINAL.js NEW.js
Output must not exist. Only three known glue sites are changed; no code executed.
"""
import pathlib,sys,hashlib
STATIC='''function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){
 var argCount=argTypes.length;
 if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}
 var isClassMethodFunc=argTypes[1]!==null&&classType!==null;
 var needsDestructorStack=usesDestructorStack(argTypes);
 var returns=argTypes[0].name!=="void";
 var destructorFunctions=argTypes.map(type=>type&&type.destructorFunction);
 var invokerFn=function(...args){
  var destructors=needsDestructorStack?[]:null;
  var wired=[cppTargetFunc];
  if(isClassMethodFunc)wired.push(argTypes[1].toWireType(destructors,this));
  for(var i=2;i<argTypes.length;i++)wired.push(argTypes[i].toWireType(destructors,args[i-2]));
  var rv=cppInvokerFunc(...wired);
  if(needsDestructorStack){runDestructors(destructors)}
  else{
   for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){
    if(destructorFunctions[i]!==null){
     var index=isClassMethodFunc?i:i-1;
     var destroy=destructorFunctions[i];destroy(wired[index]);
    }
   }
  }
  if(returns)return argTypes[0].fromWireType(rv);
 };
 Object.defineProperty(invokerFn,"length",{value:argCount-2});
 return createNamedFunction(humanName,invokerFn);
}'''
EMVAL='var __emval_get_method_caller=(argCount,argTypes,kind)=>{\n var types=emval_lookupTypes(argCount,argTypes);\n var retType=types.shift();argCount--;\n var invokerFunction=function(obj,func,destructorsRef,args){\n  var values=[],offset=0;\n  for(var i=0;i<argCount;i++){values.push(types[i].readValueFromPointer(args+offset));offset+=types[i].argPackAdvance}\n  var rv;\n  if(kind===1)rv=new func(...values);\n  else if(kind===0)rv=func.call(obj,...values);\n  else rv=func.call(...values);\n  if(!retType.isVoid)return emval_returnValue(retType,destructorsRef,rv);\n };\n var functionName=`methodCaller<(${types.map(t=>t.name).join(", ")}) => ${retType.name}>`;\n return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction));\n};'
def patch(source):
 if hashlib.sha256(source.encode()).hexdigest()!='3fb44ce11d00611f9b3f3c5775d520ebab48930c1f08279b7b1316f05f0d3379':raise ValueError('Original vendor source hash mismatch')
 start=source.index('function craftInvokerFunction(')
 end=source.index('var ensureOverloadTable=',start)
 old=source[start:end]
 expected='newFunc(Function,args)(...closureArgs)'
 if old.count(expected)!=1 or 'function craftInvokerFunction(' in source[end:]:raise ValueError('Unexpected vendor glue')
 source=source[:start]+STATIC+source[end:]
 start=source.index('var __emval_get_method_caller=');end=source.index('var __emval_get_property=',start)
 if source[start:end].count('newFunc(Function,params)(...args)')!=1:raise ValueError('Unexpected emval glue')
 source=source[:start]+EMVAL+source[end:]
 old='return function(){return Function}()("return this")()'
 if source.count(old)!=1:raise ValueError('Unexpected legacy global lookup')
 return source.replace(old,'throw new Error("A modern globalThis environment is required")')
if __name__=='__main__':
 if len(sys.argv)!=3:raise SystemExit(__doc__)
 p,q=map(pathlib.Path,sys.argv[1:]);b=p.read_bytes();out=patch(b.decode()).encode()
 with q.open('xb') as f:f.write(out)
 print('INPUT_SHA256='+hashlib.sha256(b).hexdigest())
 print('OUTPUT_SHA256='+hashlib.sha256(out).hexdigest())
