import argparse
import pathlib
import heckorator
import datetime

parser = argparse.ArgumentParser(
    "Generate large decorators from the command-line"
)

parser.add_argument(
    "-f", "--font",
    metavar="PATH",
    type=pathlib.Path,
    default=pathlib.Path(__file__).parent / "Cozette-13.bdf",
    help="Select a font file to use (default: bundled `Cozette.bdf`)"
)
actions = parser.add_subparsers()
actions.add_parser("convert", help="Convert text into heckorator format").add_argument("text")
actions.add_parser("dump", help="Dump the parsed font data to the specified path").add_argument("output_path", type=pathlib.Path)

args = parser.parse_args()
if hasattr(args, "text"):
    w, h, forward = heckorator.parse_font(str(args.font))
    backward = {c: bits for bits, c in forward.items()}
    lines = args.text.splitlines()
    maxlen = max(map(len,lines))
    padded_lines = [f"{line:<{maxlen}}" for line in lines]
    assert all(ord(c) in range(ord(" "), ord("~") + 1) for line in padded_lines for c in line), (
        "Text must be tabless printable ASCII only, sorry"
    )
    snakes = [
        [
            [["._"] * (w + 1)] + [
                ["._"] + [
                    ["._", "@_"][c == "1"]
                    for c in f"{backward[c]:0{w * h}b}"[y * w: y * w + w]
                ]
                for y in range(h)
            ]
            for c in line
        ]
        for line in padded_lines
    ]
    def transpose[T](xs: list[list[T]]) -> list[list[T]]:
        return list(map(list, zip(*xs)))
    
    def concatenate[T](xs: list[list[T]]) -> list[T]:
        return [xx for x in xs for xx in x]

    x_joined = concatenate(list(map(transpose, snakes)))
    y_joined = list(map(concatenate, x_joined))
    # snakes: ch‿cw‿bh‿bw Array str
    # x_joined: (ch×bh)‿cw‿bw Array str
    # y_joined: (ch×bh)‿(cw×bw) Array str
    padded = ["".join(row) + "._" for row in y_joined] + ["._" * ((w + 1) * maxlen + 1)]
    cap = ["@_" * ((w + 1) * maxlen + 3)]
    bordered = cap + ["@_" + row + "@_" for row in padded] + cap
    print(*bordered, sep="\n")
elif hasattr(args, "output_path"):
    data = heckorator.parse_font(str(args.font))
    with open(args.output_path, "w") as f:
        f.write(f"# Generated by `heckorator` at {datetime.datetime.now(datetime.UTC).isoformat(" ")}\n")
        f.write("font_data = ")
        f.write(repr(data))
        f.write("\n")
else:
    parser.print_help()

