import re


def add_pre_main_init(startup: str) -> str:
    """Add pw_stm32cube_Init call to startup file

    The stm32cube startup files directly call main(), while pigweed expects to
    do some setup before main is called. This could include sys_io or system
    clock initialization.

    This adds a call to `pw_stm32cube_Init()` immediately before the call to
    `main()`

    Args:
        startup: The startup script read into a string

    Returns:
        A new startup script with the `pw_stm32cube_Init()` call added.

    Raises:
        ValueError if the `main()` call is not found in `startup`
    """
    match = re.search(r'\s*bl\s+main', startup)
    if match is None:
        raise ValueError("`bl main` not found in startup script")

    return startup[:match.start(
    )] + '\nbl pw_stm32cube_Init' + startup[match.start():]