import os
from PIL import Image

# don't convert fragment_033.bin, always use original
def extract_lines_from_image(image_path):
    img = Image.open(image_path).convert("L")
    pixels = img.load()
    width, height = img.size

    horizontals = set()
    verticals = set()
    used_pixels = set()

    # Detect horizontal lines
    for y in range(height):
        x1 = None
        for x in range(width):
            if pixels[x, y] < 128:
                if x1 is None:
                    x1 = x
                x2 = x
            elif x1 is not None:
                if x2 > x1:
                    horizontals.add((x1, x2, y))
                    for xi in range(x1, x2 + 1):
                        used_pixels.add((xi, y))
                elif x2 == x1:
                    # temporarily skip single-pixel line
                    pass
                x1 = None
        if x1 is not None:
            if x2 > x1:
                horizontals.add((x1, x2, y))
                for xi in range(x1, x2 + 1):
                    used_pixels.add((xi, y))
            elif x2 == x1:
                pass

    # Detect vertical lines
    for x in range(width):
        y1 = None
        for y in range(height):
            if pixels[x, y] < 128:
                if y1 is None:
                    y1 = y
                y2 = y
            elif y1 is not None:
                if y2 > y1:
                    verticals.add((x, y1, y2))
                    for yi in range(y1, y2 + 1):
                        used_pixels.add((x, yi))
                elif y2 == y1:
                    pass
                y1 = None
        if y1 is not None:
            if y2 > y1:
                verticals.add((x, y1, y2))
                for yi in range(y1, y2 + 1):
                    used_pixels.add((x, yi))
            elif y2 == y1:
                pass

    # Detect standalone black pixels not belonging to any line
    single_pixels = set()
    for y in range(height):
        for x in range(width):
            if pixels[x, y] < 128 and (x, y) not in used_pixels:
                single_pixels.add((x, y))

    # Add single-pixel lines as horizontal ones
    for x, y in single_pixels:
        horizontals.add((x, x, y))

    return sorted(horizontals), sorted(verticals)

def save_vector_font_to_bin(horizontals, verticals, output_path):
    data = bytearray()
    for x1, x2, y in horizontals:
        data.extend([x1, x2, y])
    data.append(0xFF)
    for x, y1, y2 in verticals:
        data.extend([x, y1, y2])
    data.append(0xFF)
    with open(output_path, "wb") as f:
        f.write(data)
    print(f"✅ Saved: {output_path}")

def convert_all_images_to_vector_fonts(folder_path):
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(".png"):
            filepath = os.path.join(folder_path, filename)
            horizontals, verticals = extract_lines_from_image(filepath)
            output_path = os.path.join(folder_path, filename[:-4] + ".bin")
            save_vector_font_to_bin(horizontals, verticals, output_path)

convert_all_images_to_vector_fonts(".")