"""Minecraft 1.21.11 API migration. Native adapters live in ports/1.21.11."""
import re


def calls(text, method, rewrite):
    """Rewrite balanced Java method arguments, including nested calls and literals."""
    pattern = re.compile(r'\.' + method + r'\(')
    matches = list(pattern.finditer(text))
    for match in reversed(matches):
        start = match.end()
        depth, quoted, escaped, split, args = 1, None, False, start, []
        for i in range(start, len(text)):
            c = text[i]
            if quoted:
                if escaped: escaped = False
                elif c == '\\': escaped = True
                elif c == quoted: quoted = None
            elif c in ('"', "'"): quoted = c
            elif c in '([{': depth += 1
            elif c in ')]}':
                depth -= 1
                if depth == 0:
                    args.append(text[split:i].strip())
                    replacement = rewrite(args)
                    if replacement is not None:
                        text = text[:match.start()] + replacement + text[i+1:]
                    break
            elif c == ',' and depth == 1:
                args.append(text[split:i].strip()); split = i+1
    return text


def transform(text, relative, loader):
    if 'extends Screen' in text:
        # 1.21.11 draws the background in Screen.renderWithTooltipAndSubtitles
        # before invoking render. Calling it again throws "Can only blur once".
        text = text.replace('        renderBackground(graphics, mouseX, mouseY, partialTick);',
                            '        // The screen framework has already rendered the background.')
    if relative.name == 'PickaxeGameTests.java':
        text = text.replace('MobEffects.DIG_SLOWDOWN', 'MobEffects.MINING_FATIGUE')
    if relative.name == 'EquipmentTestBridge.java':
        text = text.replace('stack.getItem().isValidRepairItem(stack, material)', 'stack.isValidRepairItem(material)')
    if relative.name == 'ResonantSupplyAnchorLifecycle.java':
        text = text.replace('server.tell(', 'server.schedule(').replace('// tell always queues;', '// schedule always queues;')
    if loader == 'neoforge' and relative.name == 'BuilderClientEvents.java':
        text = text.replace('renderWorld(RenderLevelStageEvent event)', 'renderWorld(RenderLevelStageEvent.AfterParticles event)')
    if loader == 'forge' and relative.name in ('BuilderInteractionPolicyTest.java', 'BuilderPreviewGenerationPolicyTest.java'):
        text = text.replace('class '+relative.stem+' {', 'class '+relative.stem+''' {
    @org.junit.jupiter.api.BeforeAll
    static void bootstrapMinecraft() {
        net.minecraft.SharedConstants.tryDetectVersion();
        net.minecraft.server.Bootstrap.bootStrap();
    }
''')
    if relative.name == 'BuilderInteractionPolicyTest.java':
        text = text.replace('FletchingTableBlock.class', 'net.minecraft.world.level.block.Blocks.FLETCHING_TABLE.getClass()')
    if relative.name == 'BuilderPreviewGenerationPolicyTest.java':
        for shape, block in [('ENTITYBLOCK_ANIMATED', 'CHEST'), ('MODEL', 'STONE'), ('INVISIBLE', 'STRUCTURE_VOID')]:
            text = text.replace('RenderShape.'+shape, 'net.minecraft.world.level.block.Blocks.'+block+'.defaultBlockState()')
    if relative.name.endswith('GameTests.java'):
        text = re.sub(r'new ServerPlayer\(helper.getLevel\(\).getServer\(\), helper.getLevel\(\),\s*(new GameProfile\(UUID.randomUUID\(\), "[^"]+"\)), net.minecraft.server.level.ClientInformation.createDefault\(\)\)',
                      (r'FakePlayerFactory.get(helper.getLevel(), \1)' if loader == 'neoforge' else 'com.xfestudio.mydimension.platform.TestPlayers.survival(helper)'), text)
        text = text.replace('net.minecraft.gametest.framework.GameTest;', 'com.xfestudio.mydimension.platform.GameTest;')
        text = re.sub(r'import net\.(?:neoforged\.neoforge|minecraftforge)\.gametest\.(?:GameTestHolder|PrefixGameTestTemplate|GameTestDontPrefix);\n', '', text)
        text = re.sub(r'^@(?:GameTestHolder|PrefixGameTestTemplate|GameTestDontPrefix).*\n', '', text, flags=re.M)
        text = text.replace('player.getGameProfile(), 4, false', 'new net.minecraft.server.players.NameAndId(player.getGameProfile()), net.minecraft.server.permissions.LevelBasedPermissionSet.OWNER, false')
        text = text.replace('.deop(player.getGameProfile())', '.deop(new net.minecraft.server.players.NameAndId(player.getGameProfile()))')
        text = text.replace('player.getInventory().items)', 'java.util.stream.IntStream.range(0, 36).mapToObj(player.getInventory()::getItem).toList())')
    if relative.name == 'MyDimension.java':
        text = text.replace('ModItems.register(modEventBus);', 'ModItems.register(modEventBus);\n        com.xfestudio.mydimension.platform.PortGameTests.register(modEventBus);')
    text = text.replace('ResourceLocation', 'Identifier').replace('.location()', '.identifier()')
    text = text.replace('anchor.identifier()', 'anchor.location()').replace('context.identifier()', 'context.location()')
    text = text.replace('event.getEntity().getServer()', 'event.getEntity().level().getServer()')
    text = text.replace(', bus = EventBusSubscriber.Bus.MOD', '').replace(', bus = EventBusSubscriber.Bus.GAME', '')
    text = text.replace('readResourceLocation', 'readIdentifier').replace('writeResourceLocation', 'writeIdentifier')
    text = text.replace('net.minecraft.Util', 'net.minecraft.util.Util')
    text = text.replace('net.minecraft.world.level.GameRules', 'net.minecraft.world.level.gamerules.GameRules')
    text = text.replace('MobSpawnType', 'EntitySpawnReason')
    text = text.replace('.serverLevel()', '.level()').replace('.getMinBuildHeight()', '.getMinY()').replace('.getMaxBuildHeight()', '.getMaxY() + 1')
    text = re.sub(r'\b(player|serverPlayer|sender|owner|entity|target|actor|guest)\.getServer\(\)', r'\1.level().getServer()', text)
    text = text.replace('getGameProfile().getName()', 'getGameProfile().name()').replace('getGameProfile().getId()', 'getGameProfile().id()')
    text = text.replace('GameRules.RULE_DAYLIGHT', 'GameRules.ADVANCE_TIME').replace('GameRules.RULE_WEATHER_CYCLE', 'GameRules.ADVANCE_WEATHER')
    text = text.replace('getGameRules().getBoolean(', 'getGameRules().get(')
    text = text.replace('ItemInteractionResult', 'InteractionResult')
    text = text.replace('import net.minecraft.world.level.block.FletchingTableBlock;', '')
    text = text.replace(' || owner == FletchingTableBlock.class', '').replace('&& declaration != FletchingTableBlock.class', '')
    text = text.replace('                if (owner == FletchingTableBlock.class) return false;\n', '')
    text = text.replace('import net.minecraft.world.level.block.state.properties.DirectionProperty;', 'import net.minecraft.world.level.block.state.properties.EnumProperty;')
    text = text.replace('DirectionProperty FACING', 'EnumProperty<Direction> FACING')
    text = text.replace('getInventory().selected', 'getInventory().getSelectedSlot()')
    text = re.sub(r'\.hasPermissions\(([0-4])\)', r'.permissions().hasPermission(new net.minecraft.server.permissions.Permission.HasCommandLevel(net.minecraft.server.permissions.PermissionLevel.byId(\1)))', text)
    text = text.replace('getAllKeys()', 'keySet()')
    if relative.name != 'TagSupport.java':
        for name, default in {'Int':'0', 'Long':'0L', 'Float':'0F', 'Double':'0D', 'Byte':'(byte) 0', 'Short':'(short) 0', 'String':'""', 'Boolean':'false'}.items():
            text = calls(text, 'get'+name, lambda args,n=name,d=default: '.get'+n+'Or('+args[0]+', '+d+')' if len(args)==1 and args[0] else None)
        text = text.replace('.getCompound(', '.getCompoundOrEmpty(')
        text = calls(text, 'getList', lambda a: '.getListOrEmpty('+a[0]+')' if len(a)==2 else None)
        text = calls(text, 'hasUUID', lambda a: '.read('+a[0]+', net.minecraft.core.UUIDUtil.CODEC).isPresent()')
        text = calls(text, 'getUUID', lambda a: '.read('+a[0]+', net.minecraft.core.UUIDUtil.CODEC).orElseThrow()' if a[0] else None)
        text = calls(text, 'putUUID', lambda a: '.store('+a[0]+', net.minecraft.core.UUIDUtil.CODEC, '+a[1]+')')
        text = re.sub(r'(\b\w+)\.contains\(([^\n,()]+),\s*([\w.]*TAG_\w+|\d+)\)', r'com.xfestudio.mydimension.platform.TagSupport.contains(\1, \2, \3)', text)
        text = calls(text, 'getIntArray', lambda a: '.getIntArray('+a[0]+').orElseGet(() -> new int[0])')
    data_api = 'com.xfestudio.mydimension.platform.PlatformData'
    text = re.sub(r'(\w+)\.loadWithComponents\((\w+), '+re.escape(data_api)+r'.registries\(\1\)\)',
                  rf'\1.loadWithComponents(net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, {data_api}.registries(\1), \2))', text)
    text = text.replace('blockEntity.saveWithId('+data_api+'.registries(blockEntity))', data_api+'.saveBlockWithId(blockEntity)')
    text = text.replace('stack.getOrDefault(net.minecraft.core.component.DataComponents.BLOCK_ENTITY_DATA, net.minecraft.world.item.component.CustomData.EMPTY).copyTag()', data_api+'.blockEntityTag(stack)')
    text = text.replace('player.playNotifySound(SoundEvents.PORTAL_TRIGGER, SoundSource.PLAYERS, 0.45F, 1.15F)', 'player.connection.send(new net.minecraft.network.protocol.game.ClientboundSoundPacket(net.minecraft.core.Holder.direct(SoundEvents.PORTAL_TRIGGER), SoundSource.PLAYERS, player.getX(), player.getY(), player.getZ(), 0.45F, 1.15F, player.getRandom().nextLong()))')
    text = re.sub(r'BuiltInRegistries\.(BLOCK|ITEM).get\((\w+)\)', r'BuiltInRegistries.\1.getValue(\2)', text)
    text = text.replace('.asLookup()', '')
    text = text.replace('.onlyOpCanSetNbt()', '.getType().onlyOpCanSetNbt()')
    text = text.replace('SharedConstants.getCurrentVersion().getDataVersion().getVersion()', 'SharedConstants.getCurrentVersion().dataVersion().version()')
    text = text.replace('net.minecraft.nbt.NbtUtils.loadUUID(entry)', 'net.minecraft.core.UUIDUtil.CODEC.parse(net.minecraft.nbt.NbtOps.INSTANCE, entry).getOrThrow()')
    text = text.replace('net.minecraft.nbt.NbtUtils.createUUID(value)', 'net.minecraft.core.UUIDUtil.CODEC.encodeStart(net.minecraft.nbt.NbtOps.INSTANCE, value).getOrThrow()')
    text = text.replace('FMLEnvironment.dist ==', 'FMLEnvironment.getDist() ==')
    text = text.replace('PacketDistributor.sendToServer(', 'net.neoforged.neoforge.client.network.ClientPacketDistributor.sendToServer(') if loader == 'neoforge' else text
    text = text.replace('DimensionTransition', 'TeleportTransition').replace('EntitySpawnReason.SPAWN_EGG', 'EntitySpawnReason.SPAWN_ITEM_USE')
    text = text.replace('.noCollission()', '.noCollision()')
    text = text.replace('import net.minecraft.world.InteractionResultHolder;', '')
    text = text.replace('InteractionResultHolder<ItemStack>', 'InteractionResult')
    for method,result in [('pass','PASS'), ('consume','CONSUME'), ('fail','FAIL'), ('sidedSuccess','SUCCESS')]:
        text = re.sub(r'InteractionResultHolder.'+method+r'\(stack(?:, (?:true|false))?\)', 'InteractionResult.'+result, text)
    if relative.name == 'BuilderOperationManager.java':
        text = re.sub(r'        ItemAbility required = null;.*?        boolean tier =', '''        boolean matchingType = tool.getDestroySpeed(state) > 1.0F
                || state.is(BlockTags.MINEABLE_WITH_PICKAXE) && tool.is(net.minecraft.tags.ItemTags.PICKAXES)
                || state.is(BlockTags.MINEABLE_WITH_AXE) && tool.is(net.minecraft.tags.ItemTags.AXES)
                || state.is(BlockTags.MINEABLE_WITH_SHOVEL) && tool.is(net.minecraft.tags.ItemTags.SHOVELS)
                || state.is(BlockTags.MINEABLE_WITH_HOE) && tool.is(net.minecraft.tags.ItemTags.HOES);
        boolean tier =''', text, flags=re.S)
    if relative.name in ('ModBlocks.java', 'ModItems.java'):
        kind='BLOCK' if relative.name == 'ModBlocks.java' else 'ITEM'
        def registered(match):
            block=match[0]; name=match[1]
            marker=f'.setId(net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.{kind}, net.minecraft.resources.Identifier.fromNamespaceAndPath("mydimension", "{name}")))'
            return re.sub(r'(Properties\.(?:ofFullCopy\(Blocks.\w+\)|of\(\))|new Item.Properties\(\))', r'\1'+marker, block)
        text = re.sub(r'\.register\(\s*"([^"]+)",.*?;', registered, text, flags=re.S)
    if relative.name == 'ModEntities.java':
        text = text.replace('.build("rift_anchor")', '.build(net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.ENTITY_TYPE, net.minecraft.resources.Identifier.fromNamespaceAndPath("mydimension", "rift_anchor")))')
    if relative.name == 'ModBlockEntities.java' and loader == 'neoforge':
        text = re.sub(r'BlockEntityType.Builder.of\((\w+::new),\s*(ModBlocks.\w+.get\(\))\).build\(null\)', r'new BlockEntityType<>(\1, \2)', text)
    if relative.name == 'RealmwrightScepterItem.java':
        text = re.sub(r'    @Override\n    public void initializeClient\(.*?\n    \}', '', text, flags=re.S)
        text = text.replace('import com.xfestudio.mydimension.client.builder.RealmwrightScepterClientExtensions;', '')
        text = text.replace('inventoryTick(ItemStack stack, Level level, net.minecraft.world.entity.Entity entity,\n                              int slot, boolean selected)', 'inventoryTick(ItemStack stack, net.minecraft.server.level.ServerLevel level, net.minecraft.world.entity.Entity entity, EquipmentSlot slot)')
        text = text.replace('super.inventoryTick(stack, level, entity, slot, selected)', 'super.inventoryTick(stack, level, entity, slot)')
        text = text.replace('Item.TooltipContext context, List<Component> tooltip,', 'Item.TooltipContext context, net.minecraft.world.item.component.TooltipDisplay display, java.util.function.Consumer<Component> tooltip,')
        text = text.replace('tooltip.add(', 'tooltip.accept(')
    if relative.name == 'AnchorContainerResolver.java' and loader == 'neoforge':
        text = re.sub(r'return Optional.ofNullable\(blockEntity.getLevel\(\).getCapability\(.*?\)\);', '''var handler = blockEntity.getLevel().getCapability(net.neoforged.neoforge.capabilities.Capabilities.Item.BLOCK, blockEntity.getBlockPos(), side);
        return handler == null ? Optional.empty() : Optional.of(new com.xfestudio.mydimension.platform.TransferItemHandler(handler));''', text, flags=re.S)
    text = text.replace('state.onDestroyedByPlayer(level, pos, player, canHarvest,', 'state.onDestroyedByPlayer(level, pos, player, player.getMainHandItem(), canHarvest,')
    text = text.replace('level.neighborChanged(notification.target, sourceBlock, notification.source)', 'level.neighborChanged(notification.target, sourceBlock, null)')
    text = text.replace('Block.shouldRenderFace(state, level, pos, face, outward)', 'Block.shouldRenderFace(level, pos, state, level.getBlockState(outward), face)')
    text = calls(text, 'isSolidRender', lambda a: '.isSolidRender()')
    text = calls(text, 'teleportTo', lambda a: '.teleportTo('+', '.join(a[:4]+['java.util.Set.of()']+a[4:]+['false'])+')' if len(a)==6 else None)
    text = text.replace('.getSharedSpawnPos()', '.getRespawnData().pos()')
    text = text.replace('target.changeDimension(', 'target.teleport(')
    text = text.replace('stack.getItem(), 20', 'stack, 20').replace('addCooldown(this, 40)', 'addCooldown(stack, 40)')
    text = text.replace(', GenerationStep.Carving carving', '').replace('state, false);', 'state, 0);') if relative.name == 'SoaringMindChunkGenerator.java' else text
    if relative.name == 'RiftAnchorEntity.java':
        text = text.replace('public class RiftAnchorEntity extends Entity {', 'public class RiftAnchorEntity extends Entity {\n    @Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level, net.minecraft.world.damagesource.DamageSource source, float amount) { return false; }')
        text = text.replace('readAdditionalSaveData(CompoundTag tag)', 'readAdditionalSaveData(net.minecraft.world.level.storage.ValueInput input)')
        text = text.replace('addAdditionalSaveData(CompoundTag tag)', 'addAdditionalSaveData(net.minecraft.world.level.storage.ValueOutput output)')
        text = text.replace('ValueInput input) {', 'ValueInput input) {\n        CompoundTag tag = '+data_api+'.readTag(input);')
        text = text.replace('ValueOutput output) {', 'ValueOutput output) {\n        CompoundTag tag = new CompoundTag();')
        text = re.sub(r'(protected void addAdditionalSaveData\(.*?)(\n    \})', r'\1\n        '+data_api+r'.writeTag(output, tag);\2', text, flags=re.S)
    if relative.name == 'MeshBuilder.java':
        text = text.replace('public final class MeshBuilder implements VertexConsumer {', 'public final class MeshBuilder implements VertexConsumer {\n    @Override public VertexConsumer setLineWidth(float width) { builder.setLineWidth(width); return this; }\n    @Override public VertexConsumer setColor(int color) { builder.setColor(color); return this; }')
    if relative.name == 'ResonantSupplyAnchorBlock.java':
        text = text.replace('updateShape(BlockState state, Direction changedDirection, BlockState changedState,\n                                  LevelAccessor level, BlockPos position, BlockPos changedPosition)',
                            'updateShape(BlockState state, LevelReader level, net.minecraft.world.level.ScheduledTickAccess ticks, BlockPos position, Direction changedDirection, BlockPos changedPosition, BlockState changedState, RandomSource random)')
        start=text.index('public BlockState updateShape('); end=text.index('\n    @Override',start)
        section=text[start:end].replace('level.scheduleTick(', 'ticks.scheduleTick(').replace('super.updateShape(state, changedDirection, changedState, level, position, changedPosition)', 'super.updateShape(state, level, ticks, position, changedDirection, changedPosition, changedState, random)')
        text=text[:start]+section+text[end:]
        text = text.replace('BlockPos changedPosition, boolean moving)', 'net.minecraft.world.level.redstone.Orientation orientation, boolean moving)')
        text = text.replace('changedBlock, changedPosition, moving)', 'changedBlock, orientation, moving)')
        text = text.replace('&& changedPosition.equals(containerPosition(position, state.getValue(FACING)))', '')
        text = re.sub(r'    @Override\n    public void onRemove\(.*?\n    \}', '''    @Override
    protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos position, boolean moving) {
        super.affectNeighborsAfterRemoval(state, level, position, moving);
    }''', text, flags=re.S)
        # The block-entity lifecycle performs index removal before its level reference is cleared.
        text = text.replace('getOcclusionShape(BlockState state, BlockGetter level, BlockPos position)', 'getOcclusionShape(BlockState state)')
    if relative.name == 'ResonantSupplyAnchorBlockEntity.java':
        text = text.replace('    public enum AclResult {', '''    @Override protected void collectImplicitComponents(net.minecraft.core.component.DataComponentMap.Builder builder) {
        super.collectImplicitComponents(builder);
        builder.set(net.minecraft.core.component.DataComponents.BLOCK_ENTITY_DATA,
            net.minecraft.world.item.component.TypedEntityData.of(getType(), saveWithoutMetadata(com.xfestudio.mydimension.platform.PlatformData.registries(this))));
    }
    public enum AclResult {''')
        text = text.replace('    public enum AclResult {', '''    @Override public void preRemoveSideEffects(BlockPos position, BlockState state) {
        unregisterFromIndex();
        super.preRemoveSideEffects(position, state);
    }
    public enum AclResult {''')
    if relative.name == 'MindPortalBlock.java':
        text = text.replace('Entity entity) {', 'Entity entity, net.minecraft.world.entity.InsideBlockEffectApplier effects, boolean affectAll) {')
        text = text.replace('new Vector3f(0.08F, 0.82F, 1.0F), new Vector3f(0.76F, 0.18F, 1.0F)', '0x14D1FF, 0xC22EFF')
    if relative.name == 'MindServerLevelData.java':
        text = re.sub(r'    @Override public BlockPos getSpawnPos\(\).*?\n', '    @Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData() { return delegate.getRespawnData(); }\n', text)
        text = re.sub(r'    @Override\n    public float getSpawnAngle\(\) \{.*?\n    \}', '', text, flags=re.S)
        text = re.sub(r'    @Override\n    public void setSpawn\(.*?\n    \}', '    @Override public void setSpawn(net.minecraft.world.level.storage.LevelData.RespawnData data) { delegate.setSpawn(data); }', text, flags=re.S)
        text = text.replace('WorldBorder.Settings getWorldBorder()', 'java.util.Optional<WorldBorder.Settings> getLegacyWorldBorderSettings()').replace('delegate.getWorldBorder()', 'delegate.getLegacyWorldBorderSettings()')
        text = text.replace('setWorldBorder(WorldBorder.Settings ', 'setLegacyWorldBorderSettings(java.util.Optional<WorldBorder.Settings> ').replace('delegate.setWorldBorder(', 'delegate.setLegacyWorldBorderSettings(')
    if relative.name.endswith('BlockEntity.java'):
        text = text.replace('saveAdditional(CompoundTag tag, net.minecraft.core.HolderLookup.Provider registries)', 'saveAdditional(net.minecraft.world.level.storage.ValueOutput output)')
        text = text.replace('super.saveAdditional(tag, registries);', 'super.saveAdditional(output);\n        CompoundTag tag = new CompoundTag();')
        text = re.sub(r'(protected void saveAdditional\(.*?)(\n    \})', r'\1\n        com.xfestudio.mydimension.platform.PlatformData.writeTag(output, tag);\2', text, flags=re.S)
        text = text.replace('loadAdditional(CompoundTag tag, net.minecraft.core.HolderLookup.Provider registries)', 'loadAdditional(net.minecraft.world.level.storage.ValueInput input)')
        text = text.replace('super.loadAdditional(tag, registries);', 'super.loadAdditional(input);\n        CompoundTag tag = com.xfestudio.mydimension.platform.PlatformData.readTag(input);')
    if '/client/' in relative.as_posix():
        text = transform_client(text, relative, loader)
    return text


def transform_client(text, relative, loader):
    if relative.name == 'BuilderBlueprintClientEvents.java':
        text = text.replace('RegisterClientReloadListenersEvent', 'AddClientReloadListenersEvent')
        text = text.replace('event.registerReloadListener(', 'event.addListener(net.minecraft.resources.Identifier.fromNamespaceAndPath("mydimension", "preview_cache"), ')
    for modifier in ('Alt', 'Control', 'Shift'):
        text = text.replace(f'Screen.has{modifier}Down()', f'net.minecraft.client.Minecraft.getInstance().has{modifier}Down()')
    text = text.replace('Direction.getNearest((float)', 'Direction.getApproximateNearest((float)')
    text = text.replace('currentEdges.getLongOr(index, 0L)', 'currentEdges.getLong(index)')
    text = text.replace('protected void renderWidget(', 'protected void renderContents(')
    text = text.replace('super.renderWidget(', 'super.renderContents(')
    text = text.replace('keyPressed(int keyCode, int scanCode, int modifiers) {', 'keyPressed(net.minecraft.client.input.KeyEvent keyEvent) {\n        int keyCode = keyEvent.key(), scanCode = keyEvent.scancode(), modifiers = keyEvent.modifiers();')
    text = text.replace('super.keyPressed(keyCode, scanCode, modifiers)', 'super.keyPressed(keyEvent)')
    text = text.replace('graphics.pose().pushPose()', 'graphics.pose().pushMatrix()').replace('graphics.pose().popPose()', 'graphics.pose().popMatrix()')
    text = re.sub(r'graphics.pose\(\).(translate|scale)\(([^,\n]+), ([^,\n]+), [^,\n]+\)', r'graphics.pose().\1(\2, \3)', text)
    if relative.name == 'BuilderKeyMappings.java':
        text = re.sub(r'public static final String CATEGORY = "[^"]+";', 'public static final KeyMapping.Category CATEGORY = KeyMapping.Category.register(net.minecraft.resources.Identifier.fromNamespaceAndPath("mydimension", "builder"));', text)
    if relative.name == 'BuilderPreviewSectionMeshCache.java':
        text = text.replace('requiresBlockEntityGhost(cell.state().getRenderShape())', 'requiresBlockEntityGhost(cell.state())')
        text = text.replace('requiresBlockEntityGhost(RenderShape renderShape)', 'requiresBlockEntityGhost(BlockState state)')
        text = text.replace('return renderShape == RenderShape.ENTITYBLOCK_ANIMATED;', 'return state.hasBlockEntity();')
        # Modern blocks can have both baked quads and a block-entity renderer.
        # A chest's baked model is empty; a furnace's renderer is absent.
        text = text.replace('} else if (cell.state().getRenderShape() == RenderShape.MODEL)', '} if (cell.state().getRenderShape() == RenderShape.MODEL)')
        text = text.replace('&& cell.state().getRenderShape() != RenderShape.INVISIBLE;', '&& (cell.state().getRenderShape() != RenderShape.INVISIBLE || requiresBlockEntityGhost(cell.state()));')
        text = text.replace('import net.minecraft.client.resources.model.BakedModel;', 'import net.minecraft.client.renderer.block.model.BlockStateModel;')
        text = re.sub(r'import net\.(?:neoforged\.neoforge|minecraftforge)\.client\.model\.data\.ModelData;\n', '', text)
        text = text.replace('BakedModel model', 'BlockStateModel model')
        text = re.sub(r'for \(RenderType renderType : model.getRenderTypes\(\s*cell.state\(\), renderTypeRandom, ModelData.EMPTY\)\)', 'for (var part : model.collectParts(renderTypeRandom))', text)
        text = re.sub(r'model.getQuads\(cell.state\(\), (direction|null), \w+,\s*ModelData.EMPTY, renderType\)', r'part.getQuads(\1)', text)
        text = text.replace('minecraft.getBlockEntityRenderDispatcher().renderItem(blockEntity, pose, source,\n                    LightTexture.FULL_BRIGHT, OverlayTexture.NO_OVERLAY);', 'com.xfestudio.mydimension.platform.MeshCapture.render(blockEntity, pose, source);')
        text = text.replace('renderShape == RenderShape.ENTITYBLOCK_ANIMATED', 'renderShape == RenderShape.INVISIBLE')
        text = text.replace('state, context.blocks, pos, direction, context.neighbour', 'context.blocks, pos, state, context.blocks.getBlockState(context.neighbour), direction')
        text = text.replace('getMinBuildHeight()', 'getMinY()')
        text = text.replace('private static final class GhostVertexConsumer implements VertexConsumer {', '''private static final class GhostVertexConsumer implements VertexConsumer {
        @Override public VertexConsumer setLineWidth(float width) { delegate.setLineWidth(width); return this; }
        @Override public VertexConsumer setColor(int color) { return setColor(color >> 16 & 255, color >> 8 & 255, color & 255, color >>> 24); }''')
    if relative.name == 'ModClientEvents.java':
        text = re.sub(r'import .*RegisterShadersEvent;\n', '', text)
        text = re.sub(r'    @SubscribeEvent\n    public static void registerShaders\(.*?\n    \}', '', text, flags=re.S)
        text = re.sub(r'    @SubscribeEvent\n    public static void registerAdditionalModels\(.*?\n    \}', '''    @SubscribeEvent
    public static void registerSpecialModels(net.neoforged.neoforge.client.event.RegisterSpecialModelRendererEvent event) {
        event.register(net.minecraft.resources.Identifier.fromNamespaceAndPath("mydimension", "scepter"), RealmwrightScepterRenderer.Unbaked.CODEC);
    }''', text, flags=re.S)
        text = text.replace('MindPortalOverlay.OVERLAY', 'MindPortalOverlay::render')
    text = text.replace('net.minecraft.client.renderer.RenderType;', 'net.minecraft.client.renderer.rendertype.RenderType;')
    text = text.replace('import com.mojang.blaze3d.vertex.VertexBuffer;', 'import com.xfestudio.mydimension.platform.VertexBuffer;')
    text = text.replace('import net.minecraft.client.renderer.ShaderInstance;', '')
    text = text.replace('ShaderInstance shader = RenderSystem.getShader();', 'RenderType shader = renderType;')
    text = text.replace('RenderSystem.setShaderColor(', 'com.xfestudio.mydimension.platform.PreviewDrawState.setShaderColor(')
    text = re.sub(r'\s*(?:renderType\.(?:setup|clear)RenderState|VertexBuffer.unbind|buffer.bind|RenderSystem.enableBlend|RenderSystem.disableBlend|RenderSystem.defaultBlendFunc|BuilderPreviewRenderTypes.updateWaveUniforms)\(\);', '', text)
    text = text.replace('RenderSystem.recordRenderCall(buffer::close)', 'net.minecraft.client.Minecraft.getInstance().execute(buffer::close)')
    text = calls(text, 'drawWithShader', lambda a: '.drawWithShader('+a[0]+', null, '+a[2]+')' if len(a)==3 else None)
    text = text.replace('FOCUSED_OUTLINE_CACHE.draw(poseStack, event.getProjectionMatrix(),', 'FOCUSED_OUTLINE_CACHE.draw(poseStack, null,')
    if relative.name == 'BuilderPreviewRenderer.java':
        text = text.replace('if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES) return;', 'if (!(event instanceof RenderLevelStageEvent.AfterParticles)) return;\n        var frame = com.xfestudio.mydimension.platform.PreviewFrame.get(event);\n        if (frame == null) return;')
        text = text.replace('event.getPartialTick().getGameTimeDeltaPartialTick(false)', 'frame.partialTick()')
        text = text.replace('event.getCamera().getPosition()', 'frame.camera()').replace('event.getFrustum()', 'frame.frustum()')
        text = text.replace('PoseStack poseStack = event.getPoseStack();', 'PoseStack poseStack = new PoseStack();\n        poseStack.mulPose(event.getModelViewMatrix());')
    if relative.name == 'BuilderClientEvents.java' and loader == 'neoforge':
        text = text.replace('    @SubscribeEvent\n    public static void renderWorld', '''    @SubscribeEvent
    public static void extractPreview(net.neoforged.neoforge.client.event.ExtractLevelRenderStateEvent event) {
        com.xfestudio.mydimension.platform.PreviewFrame.extract(event);
    }

    @SubscribeEvent
    public static void renderWorld''')
    return text
