"""
This process can be used to transmit a SIGINT or SIGBREAK signal to child process reliably. For correct behaviour
the target process must be created with CREATE_NEW_CONSOLE. Since this script removes itself from the console it
starts with the creationflags shall be CREATE_NEW_PROCESS_GROUP.
"""
import argparse

import pywintypes
import win32api
import win32con
import win32console


def send_console_event(pid: int, ctrl_break: bool = False) -> bool:
    # NOTE: This may return success even if the remote has no handler, we can't tell the difference.
    try:
        win32console.FreeConsole()  # ignore returned failure, it should indicate no prior console
        if not win32console.AttachConsole(pid):  # this may raise if the target process has no console
            if not win32api.GenerateConsoleCtrlEvent(
                win32con.CTRL_BREAK_EVENT if ctrl_break else win32con.CTRL_C_EVENT, 0
            ):
                return True
    except pywintypes.error:
        return False
    return False


def main():
    parser = argparse.ArgumentParser("Clarabot Nano - Windows child process signal transmitter")
    parser.add_argument("pid", type=int, help="Process id of the child to attach to and signal.")
    parser.add_argument("--ctrl_break", action="store_true", help="Send Ctrl+Break signal instead of Ctrl+C.")
    args = parser.parse_args()
    send_console_event(args.pid, args.ctrl_break)


if __name__ == "__main__":
    main()
