#!/usr/bin/env python3

from PIL import Image
import sys

if len(sys.argv) != 3:
    print(f"Usage: {sys.argv[0]} input.jpg output.txt")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

# VTI display resolution
WIDTH = 128
HEIGHT = 48

# Bit positions:
# 5 2
# 4 1
# 3 0

BIT_MAP = [
    (0, 0, 5),
    (1, 0, 2),
    (0, 1, 4),
    (1, 1, 1),
    (0, 2, 3),
    (1, 2, 0)
]

img = Image.open(input_file)

# Convert to grayscale
img = img.convert("L")

# Resize to VTI display pixel resolution
img = img.resize((WIDTH, HEIGHT), Image.LANCZOS)

# Convert to monochrome
threshold = 128
pixels = img.load()

for y in range(HEIGHT):
    for x in range(WIDTH):
        pixels[x, y] = 1 if pixels[x, y] < threshold else 0

hex_bytes = []

# Process 64 x 16 character blocks
for row in range(16):
    for col in range(64):

        value = 0

        for dx, dy, bit in BIT_MAP:
            px = col * 2 + dx
            py = row * 3 + dy

            if pixels[px, py]:
                value |= (1 << bit)

        hex_bytes.append(f"{value:02X}")

output = "".join(hex_bytes)

with open(output_file, "w") as f:
    f.write(output)

print(f"Wrote {len(output)} hex characters to {output_file}")