"""
``vc2-test-case-generator-worker``
==================================

Scripts involving this command are generated by ``vc2-test-case-generator``
when the ``--parallel`` argument is given. You should not use this command
except as emitted by ``vc2-test-case-generator``.

Internals
=========

This command executes the pickled callable passed via its single commandline
argument. The callable is pickled, zlib compressed and url-safe base64 encoded.

The :py:func:`create_command` function can be passed a callable and its
arguments to produce a ``vc2-test-case-generator-worker`` argument.
"""

import pickle

import base64

import zlib

from functools import partial


def encode(fn, *args, **kwargs):
    return base64.urlsafe_b64encode(
        zlib.compress(pickle.dumps(partial(fn, *args, **kwargs)))
    ).decode("ascii")


def decode(encoded_function_call):
    return pickle.loads(
        zlib.decompress(base64.urlsafe_b64decode(encoded_function_call.encode("ascii")))
    )


def create_command(fn, *args, **kwargs):
    """
    Create a ``vc2-test-case-generator-worker`` command which can be used to
    execute the provided callable with the specified arguments.
    """
    return "vc2-test-case-generator-worker {}".format(encode(fn, *args, **kwargs))


def main(*args, **kwargs):
    from argparse import ArgumentParser

    parser = ArgumentParser(
        description="""
        Generate a subset of test cases. This command should only be used as
        directed by vc2-test-case-generator.
    """
    )
    parser.add_argument("code")
    args = parser.parse_args(*args, **kwargs)
    fn = decode(args.code)
    fn()


if __name__ == "__main__":
    main()
