#!/usr/bin/env python3
"""
png2gds.py - Convert a black & white PNG into a photolithography GDSII pattern.

Key idea
--------
The image is resampled to an adjustable grid of  N_x x N_y  "pixels".
Each pixel becomes a square of side  PIXEL_SIZE (um)  in the GDS.
Choose PIXEL_SIZE >= the minimum feature your litho tool can resolve
(typically 1-2 um), so even a single isolated pixel is printable.

Total pattern size = (N_x * PIXEL_SIZE) x (N_y * PIXEL_SIZE)

Examples
--------
# 200 pixels wide (height from aspect ratio), 2 um pixels -> 400 um wide
python png2gds.py logo.png out.gds --nx 200 --pixel-size 2

# Explicit grid 300 x 150 pixels, 1.5 um pixels, dark = no metal (invert)
python png2gds.py logo.png out.gds --nx 300 --ny 150 --pixel-size 1.5 --invert

# Fit pattern into a given physical width (pixel size computed, then checked)
python png2gds.py logo.png out.gds --nx 250 --width 500
"""

import argparse
import sys

import numpy as np
import gdstk
from PIL import Image


# ----------------------------------------------------------------------------
# Image handling
# ----------------------------------------------------------------------------
def load_bitmap(path, nx=None, ny=None, threshold=128, invert=False):
    """
    Load an image and return a boolean array (ny, nx); True = pattern/exposed.

    nx, ny : number of pixels in the output grid.
             If only one is given, the other follows the image aspect ratio.
             If neither is given, the native image resolution is used.
    threshold : 0-255, gray values BELOW this count as 'black'.
    invert : if False, black pixels -> pattern.  If True, white pixels -> pattern.
    """
    img = Image.open(path)

    # Flatten transparency onto a white background
    if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
        img = img.convert("RGBA")
        bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
        img = Image.alpha_composite(bg, img)
    img = img.convert("L")

    w, h = img.size
    if nx is None and ny is None:
        nx, ny = w, h
    elif ny is None:
        ny = max(1, round(nx * h / w))
    elif nx is None:
        nx = max(1, round(ny * w / h))

    if (nx, ny) != (w, h):
        # Area-average when shrinking (avoids aliasing); nearest when enlarging
        method = Image.BOX if (nx < w or ny < h) else Image.NEAREST
        img = img.resize((nx, ny), method)

    arr = np.asarray(img)
    mask = arr < threshold          # black = True
    if invert:
        mask = ~mask
    return mask


# ----------------------------------------------------------------------------
# Bitmap -> rectangles (run-length encoding + vertical merging)
# ----------------------------------------------------------------------------
def _row_runs(row):
    """Return list of (x_start, x_end) for consecutive True runs in a 1-D bool row."""
    padded = np.concatenate(([0], row.astype(np.int8), [0]))
    d = np.diff(padded)
    starts = np.where(d == 1)[0]
    ends = np.where(d == -1)[0]
    return list(zip(starts.tolist(), ends.tolist()))


def bitmap_to_rects(mask):
    """
    Merge pixels into as few rectangles as possible.
    Horizontal runs are found per row; identical runs on consecutive rows
    are stacked into one taller rectangle.
    Returns list of (x0, x1, row0, row1) in pixel units (row 0 = top of image).
    """
    ny, _ = mask.shape
    active = {}      # (x0, x1) -> starting row
    rects = []
    for row in range(ny + 1):
        runs = set(_row_runs(mask[row])) if row < ny else set()
        for key in [k for k in active if k not in runs]:
            rects.append((key[0], key[1], active.pop(key), row))
        for r in runs:
            if r not in active:
                active[r] = row
    return rects


# ----------------------------------------------------------------------------
# GDS writing
# ----------------------------------------------------------------------------
def build_gds(mask, pixel_size, out_path, layer=1, datatype=0,
              cell_name="PNG_PATTERN", merge=True, mirror_x=False,
              bounding_box_layer=None):
    ny, nx = mask.shape
    p = round(pixel_size, 3)  # snap to 1 nm grid

    rects = bitmap_to_rects(mask)
    polys = []
    for x0, x1, r0, r1 in rects:
        # GDS y axis points up, image rows point down -> flip
        xa, xb = x0 * p, x1 * p
        ya, yb = (ny - r1) * p, (ny - r0) * p
        if mirror_x:  # mirror horizontally (e.g. for emulsion-down masks)
            xa, xb = nx * p - xb, nx * p - xa
        polys.append(gdstk.rectangle((xa, ya), (xb, yb),
                                     layer=layer, datatype=datatype))

    n_before = len(polys)
    if merge and polys:
        # Union removes internal edges between touching rectangles
        polys = gdstk.boolean(polys, [], "or", precision=1e-3,
                              layer=layer, datatype=datatype)

    lib = gdstk.Library(unit=1e-6, precision=1e-9)   # 1 GDS unit = 1 um
    cell = lib.new_cell(cell_name)
    cell.add(*polys)

    if bounding_box_layer is not None:
        cell.add(gdstk.rectangle((0, 0), (nx * p, ny * p),
                                 layer=bounding_box_layer, datatype=0))

    lib.write_gds(out_path)
    return n_before, len(polys), (nx * p, ny * p)


# ----------------------------------------------------------------------------
# CLI
# ----------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser(description="Convert a B/W PNG to a litho GDS.")
    ap.add_argument("png", help="input image")
    ap.add_argument("gds", help="output .gds file")

    g = ap.add_argument_group("pixel grid")
    g.add_argument("--nx", type=int, help="number of pixels along X")
    g.add_argument("--ny", type=int, help="number of pixels along Y "
                                          "(default: keep aspect ratio)")
    g.add_argument("--pixel-size", type=float, default=2.0,
                   help="side of each pixel in um (default 2.0)")
    g.add_argument("--width", type=float,
                   help="total pattern width in um; overrides --pixel-size "
                        "(pixel size = width / nx)")

    g = ap.add_argument_group("tool / image options")
    g.add_argument("--min-feature", type=float, default=1.0,
                   help="litho resolution limit in um (default 1.0; use 2.0 "
                        "to be conservative)")
    g.add_argument("--threshold", type=int, default=128,
                   help="B/W threshold 0-255 (default 128)")
    g.add_argument("--invert", action="store_true",
                   help="white pixels become pattern instead of black")
    g.add_argument("--mirror", action="store_true",
                   help="mirror pattern left-right")

    g = ap.add_argument_group("GDS options")
    g.add_argument("--layer", type=int, default=1)
    g.add_argument("--datatype", type=int, default=0)
    g.add_argument("--cell", default="PNG_PATTERN")
    g.add_argument("--no-merge", action="store_true",
                   help="skip boolean union (faster for huge images)")
    g.add_argument("--bbox-layer", type=int, default=None,
                   help="also draw the pattern bounding box on this layer")
    args = ap.parse_args()

    mask = load_bitmap(args.png, args.nx, args.ny, args.threshold, args.invert)
    ny, nx = mask.shape

    pixel_size = args.pixel_size
    if args.width is not None:
        pixel_size = args.width / nx

    # --- resolution sanity checks --------------------------------------
    if pixel_size < args.min_feature:
        print(f"WARNING: pixel size {pixel_size:.3f} um is below the tool "
              f"resolution ({args.min_feature} um). Single pixels and thin "
              f"lines may not print. Reduce --nx/--ny or increase "
              f"--pixel-size/--width.", file=sys.stderr)
        max_nx = int((args.width or pixel_size * nx) / args.min_feature)
        print(f"         For this total width, use at most ~{max_nx} pixels "
              f"in X.", file=sys.stderr)

    n_rect, n_poly, (W, H) = build_gds(
        mask, pixel_size, args.gds, args.layer, args.datatype, args.cell,
        merge=not args.no_merge, mirror_x=args.mirror,
        bounding_box_layer=args.bbox_layer)

    fill = 100 * mask.mean()
    print(f"Grid          : {nx} x {ny} pixels ({fill:.1f}% filled)")
    print(f"Pixel size    : {pixel_size:.3f} um")
    print(f"Pattern size  : {W:.1f} x {H:.1f} um")
    print(f"Rectangles    : {n_rect}  ->  polygons after merge: {n_poly}")
    print(f"Written to    : {args.gds}")


if __name__ == "__main__":
    main()
