# File generated by Setupinit
import sys
import paradict

__all__ = []

import paradict.io_bin

import paradict.io_text

TEXT = """\
Paradict - Streamable multi-format serialization
https://github.com/pyrustic/paradict

COMMANDS:
    t2b <src> [<dst>]: Text-to-binary serialization.
    b2t <src> [<dst>]: Binary-to-text serialization.

NOTES:
    - Serialization is done from a src file to a dst file.
    - <src> is an existing filename.
    - <dst> is an optional filename (that exists or not).

To show this help message, type '-h' or '--help'.
"""


def main():
    all_args = sys.argv[1:]
    try:
        command = all_args[0]
    except IndexError as e:
        print(TEXT)
        return
    args = all_args[1:]
    if command in ("-h", "--help"):
        print(TEXT)
        return
    handler = HANDLERS.get(command)
    if handler is None:
        print("Invalid command. Type -h for help.")
    else:
        handler(args)


def t2b(args):
    args = ensure_args(args)
    if not args:
        return
    src, dst = args
    data = paradict.io_text.read(src)
    if dst:
        paradict.io_bin.pack_into(data, dst)
    else:
        print(paradict.pack(data))


def b2t(args):
    args = ensure_args(args)
    if not args:
        return
    src, dst = args
    data = paradict.io_bin.unpack_from(src)
    if dst:
        paradict.io_text.write(data, dst)
    else:
        print(paradict.encode(data))


def ensure_args(args):
    if not args:
        print("Error: The 'src' argument is required but was not provided.")
    elif len(args) == 1:
        return args[0], None
    elif len(args) == 2:
        return args
    else:
        print("Error: Too many arguments.")


HANDLERS = {"t2b": t2b, "b2t": b2t}


if __name__ == "__main__":
    main()
