from geo.render.canvas import Canvas

BRAILLE_BASE = 0x2800

# Bit positions for a 2x4 braille cell.
# Column 0 (left):  rows 0-3 -> bits 0,1,2,6
# Column 1 (right): rows 0-3 -> bits 3,4,5,7
DOT_BITS = [
    [0x01, 0x08],  # row 0
    [0x02, 0x10],  # row 1
    [0x04, 0x20],  # row 2
    [0x40, 0x80],  # row 3
]


def encode_braille(canvas: Canvas) -> list[str]:
    """Convert a pixel canvas to lines of Unicode braille characters."""
    lines = []
    for char_y in range(canvas.char_height):
        line = []
        for char_x in range(canvas.char_width):
            code = 0
            for dy in range(4):
                for dx in range(2):
                    px = char_x * 2 + dx
                    py = char_y * 4 + dy
                    if canvas.get_pixel(px, py):
                        code |= DOT_BITS[dy][dx]
            line.append(chr(BRAILLE_BASE + code))
        lines.append("".join(line))
    return lines
