from itertools import chain
from typing import Sequence

from clarabot_nano_common.utility.serialize import uint2bytes

from clarabot_nano.common.spawn.constants import SECRET_ARGUMENTS_PREAMBLE


def write_secret_arguments(stream, arguments: Sequence[bytes], preamble=SECRET_ARGUMENTS_PREAMBLE):
    message = b"".join(
        chain(
            *[
                (
                    preamble,
                    uint2bytes(len(arguments)),
                ),
                chain(
                    *[
                        (
                            uint2bytes(len(a)),
                            a,
                        )
                        for a in arguments
                    ]
                ),
            ]
        )
    )
    stream.write(message)


def write_tight_python_arguments(stream, core_port: int, core_auth_data: bytes):
    write_secret_arguments(stream, [str(core_port).encode("ascii"), core_auth_data])
