from prompt_toolkit.layout.containers import ConditionalContainer, Container
from prompt_toolkit.layout.dimension import Dimension
from prompt_toolkit.layout.mouse_handlers import MouseHandlers
from prompt_toolkit.layout.screen import Screen, WritePosition

_PATCHED: bool = False

def patch_conditional_container() -> None:
    """Render-time compat with PTK 3.0.51: hide inactive branch entirely."""
    global _PATCHED
    if _PATCHED:
        return


def preferred_width(self, max_available_width: int) -> Dimension:
    if self.filter():
        return self.content.preferred_width(max_available_width)
    else:
        return Dimension.zero()

def preferred_height(self, width: int, max_available_height: int) -> Dimension:
    if self.filter():
        return self.content.preferred_height(width, max_available_height)
    else:
        return Dimension.zero()

def write_to_screen(
    self,
    screen: Screen,
    mouse_handlers: MouseHandlers,
    write_position: WritePosition,
    parent_style: str,
    erase_bg: bool,
    z_index: int | None,
) -> None:
    if self.filter():
        return self.content.write_to_screen(
            screen, mouse_handlers, write_position, parent_style, erase_bg, z_index
        )

def get_children(self) -> list[Container]:
    result = [self.content]
    return result


# Monkey-patch methods.
ConditionalContainer.preferred_width = preferred_width
ConditionalContainer.preferred_height = preferred_height
ConditionalContainer.write_to_screen = write_to_screen
ConditionalContainer.get_children = get_children
_PATCHED = True
