if something needs $OUTPUT or $PAGE it has to be moved to the page renderer or refactored so that instead of globals the renderer is passed into the function
in any case this needs a lot of review + refactoring + tons of improvements because it is not designed in the best way