import argparse

from .core import (
    bool_matrix_to_bytes,
    bytes_to_bool_matrix,
    format_hexdump,
    interactive_edit_bitmap,
    load_image,
    preview_from_bytes,
    to_monochrome_bytes,
)


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Create monochrome bitmap hexdump from image.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("-i", "--input", required=True, help="Input image file (png, jpg, svg, bmp, ...)")
    parser.add_argument("-H", "--height", type=int, required=True, help="Target height in pixels (1-255)")
    parser.add_argument("-w", "--width", type=int, required=True, help="Target width in pixels (1-255)")
    parser.add_argument(
        "-t",
        "--threshold",
        type=int,
        default=5,
        help="Threshold level between white and black (0-10)",
    )
    parser.add_argument(
        "-s",
        "--scale",
        type=int,
        default=4,
        help="Pixel scale for interactive editor (logical pixel = s x s screen pixels)",
    )

    args = parser.parse_args()

    if not (1 <= args.height <= 255 and 1 <= args.width <= 255):
        raise SystemExit("height and width must be in range 1..255")
    if not (0 <= args.threshold <= 10):
        raise SystemExit("threshold must be in range 0..10")

    img = load_image(args.input, args.width, args.height)
    data = to_monochrome_bytes(img, args.threshold)

    try:
        bitmap = bytes_to_bool_matrix(args.width, args.height, data)
        edited_bitmap = interactive_edit_bitmap(args.width, args.height, bitmap, args.scale)
        data = bool_matrix_to_bytes(args.width, args.height, edited_bitmap)
    except Exception:
        pass

    preview_from_bytes(args.width, args.height, data)
    output = format_hexdump(args.height, args.width, data)
    print(output)
