#!python

import sys
import argparse

from python_modhex import python_modhex
from python_modhex._version import __version__

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Modhex converter for yubikey OTPs.",
        formatter_class=argparse.RawTextHelpFormatter,
        allow_abbrev=False,
    )
    parser.add_argument(
        "--version",
        action="version",
        version="%(prog)s {version}".format(version=__version__),
    )

    # subparsers
    subparsers = parser.add_subparsers(help="Sub commands.", dest="subcommand")
    subparsers.required = True

    from_modhex = subparsers.add_parser(
        "from-modhex",
        help="Convert hex to modhex.",
        description="Convert hex to modhex.",
        formatter_class=argparse.RawTextHelpFormatter,
        allow_abbrev=False,
    )

    from_modhex.add_argument(
        "modhex_values",
        type=str,
        nargs="+",
        help="Modhex values.",
    )
    
    to_modhex = subparsers.add_parser(
        "to-modhex",
        help="Convert modhex to hex.",
        description="Convert modhex to hex.",
        formatter_class=argparse.RawTextHelpFormatter,
        allow_abbrev=False,
    )

    to_modhex.add_argument(
        "hex_values",
        type=str,
        nargs="+",
        help="Hex values.",
    )

    args = parser.parse_args()

    if args.subcommand == "from-modhex":
        values = args.modhex_values
        for value in values:
            try:
                print(f"{value} -> {python_modhex.from_modhex(value)}")
            except (ValueError) as e:
                print(str(e))

    if args.subcommand == "to-modhex":
        values = args.hex_values
        for value in values:
            try:
                print(f"{value} -> {python_modhex.to_modhex(value)}")
            except (ValueError) as e:
                print(f"{value} {str(e)}")
