#!/usr/bin/env python3
"""Build 3D-printable STL files for the baby-shark tessellation puzzle.

Reads the tile drawn in TesselManiac! (BabyShark8.svg), works out how the
sharks interlock (a shark plus its 180-degree-rotated partner repeats on a
lattice), and writes:

    stl/tile.stl              one shark tile (print-ready)
    stl/tiles_color_A.stl     a print plate of the "upright" sharks
    stl/tiles_color_B.stl     a print plate of the "upside-down" partner sharks
    stl/board.stl             recessed board the tiles drop into
    stl/qr_plaque.stl         plaque with a QR code linking to the website
    stl/preview.png           top-down picture of the assembled puzzle

Usage:
    .venv/bin/python make_stl.py --url https://your-domain.us.com
    .venv/bin/python make_stl.py --scale 0.18 --area 180x140 --gap 0.4

All lengths are millimetres. Change the defaults below or pass flags.
"""
import argparse
import re
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import segno
import trimesh
from shapely import affinity
from shapely.geometry import LineString, Point, Polygon, box
from shapely.ops import unary_union

HERE = Path(__file__).resolve().parent

# Approximate lattice vectors of the shark pair, in SVG pixels. They are found
# by image search and then refined from the tile's own vertices (refine_vector).
V1_APPROX = (84.0, -183.5)
V2_APPROX = (346.0, 209.5)
# Midpoint of the straight bottom edge (SVG pixels): the 180-degree turn centre.
HALF_TURN_PX = (296.01, 302.25)

# ----------------------------------------------------------------------------
# SVG reading
# ----------------------------------------------------------------------------
NUM = r"-?\d+(?:\.\d+)?"


def parse_points(text):
    return [(float(a), float(b)) for a, b in re.findall(rf"({NUM})\s*,\s*({NUM})", text)]


def read_svg(path):
    """Return (outline, polylines, ellipses) in SVG pixels for the FIRST tile.

    TesselManiac! writes the tile twice (a filled copy, then an outline-only
    copy lower down the page). Only the first copy is used.
    """
    src = Path(path).read_text()
    texts = [m.start() for m in re.finditer(r"<text", src)]
    first = src[: texts[1]] if len(texts) > 1 else src
    outline = parse_points(re.search(r'<polygon[^>]*points\s*=\s*"([^"]+)"', first).group(1))
    lines = [parse_points(m) for m in re.findall(r'<polyline[^>]*points\s*=\s*"([^"]+)"', first)]
    ellipses = []
    for m in re.finditer(r"<ellipse([^>]*)/>", first):
        a = dict(re.findall(r'(\w+)\s*=\s*"\s*([^"]+?)\s*"', m.group(1)))
        ellipses.append(tuple(float(a[k]) for k in ("cx", "cy", "rx", "ry")))
    return outline, lines, ellipses


# ----------------------------------------------------------------------------
# Lattice
# ----------------------------------------------------------------------------
def refine_vector(verts, approx, tol=3.0):
    """Snap an approximate lattice vector to the exact one using vertex pairs.

    TesselManiac! samples matching edges identically, so many vertex pairs differ
    by exactly the lattice vector. The most common difference near `approx` wins.
    """
    diffs = (verts[None, :, :] - verts[:, None, :]).reshape(-1, 2)
    near = diffs[np.hypot(*(diffs - approx).T) < tol]
    if len(near) < 5:
        return np.array(approx)
    # densest cluster: median of the points closest to the overall median
    med = np.median(near, axis=0)
    close = near[np.hypot(*(near - med).T) < 0.3]
    return close.mean(axis=0) if len(close) >= 3 else med


# ----------------------------------------------------------------------------
# Meshes
# ----------------------------------------------------------------------------
def extrude(geom, height, z0=0.0):
    """Extrude a (Multi)Polygon into watertight prisms from z0 to z0+height."""
    if geom.is_empty or height <= 0:
        return []
    polys = [geom] if geom.geom_type == "Polygon" else list(geom.geoms)
    meshes = []
    for p in polys:
        if p.is_empty or p.area < 1e-6:
            continue
        m = trimesh.creation.extrude_polygon(p, height, engine="earcut")
        m.apply_translation([0, 0, z0])
        meshes.append(m)
    return meshes


def combine(meshes):
    meshes = [m for m in meshes if m is not None]
    return trimesh.util.concatenate(meshes) if meshes else None


def try_union(meshes):
    """Boolean-union when manifold3d is installed, else plain concatenation.

    Slicers accept overlapping/touching shells, so concatenation is fine.
    """
    try:
        return trimesh.boolean.union(meshes, engine="manifold")
    except Exception:
        return combine(meshes)


def save(mesh, path):
    path.parent.mkdir(parents=True, exist_ok=True)
    mesh.export(path)
    b = mesh.bounds
    size = b[1] - b[0]
    print(f"  {path.name:22s} {size[0]:6.1f} x {size[1]:6.1f} x {size[2]:4.1f} mm  "
          f"{len(mesh.faces):7d} triangles  watertight={mesh.is_watertight}")


# ----------------------------------------------------------------------------
# Puzzle geometry
# ----------------------------------------------------------------------------

def fill_rectangle(tile0, rot, v1, v2, area):
    """Choose the lattice offset that fits the most WHOLE tiles inside a w x h box.

    Returns [(kind, polygon)] for one connected group, kind "A" = upright shark,
    "B" = its 180-degree partner.
    """
    w, h = area
    rect = box(0, 0, w, h)
    base = {"A": tile0, "B": rot(tile0)}
    best = None
    steps = 14
    for fa in np.linspace(0, 1, steps, endpoint=False):
        for fb in np.linspace(0, 1, steps, endpoint=False):
            shift = fa * v1 + fb * v2 + np.array([-w / 2, -h / 2])
            found = []
            for i in range(-8, 9):
                for j in range(-8, 9):
                    off = i * v1 + j * v2 + shift + np.array([w / 2, h / 2])
                    for kind in "AB":
                        poly = affinity.translate(base[kind], *off)
                        if poly.within(rect):
                            found.append((kind, poly))
            if not found:
                continue
            # keep the largest edge-connected group so no tile floats alone
            glued = unary_union([p.buffer(0.05) for _, p in found])
            groups = [glued] if glued.geom_type == "Polygon" else list(glued.geoms)
            main = max(groups, key=lambda gg: sum(1 for _, p in found if gg.contains(p.representative_point())))
            keep = [(k, p) for k, p in found if main.contains(p.representative_point())]
            na = sum(1 for k, _ in keep if k == "A")
            score = (len(keep), -abs(na - (len(keep) - na)))
            if best is None or score > best[0]:
                best = (score, keep)
    return best[1] if best else []

def place_grid(tile0, rot, v1, v2, ni, nj):
    """Lay out ni x nj lattice cells (each = one shark + its 180-degree partner)."""
    base = {"A": tile0, "B": rot(tile0)}
    placed = []
    for i in range(ni):
        for j in range(nj):
            off = i * v1 + j * (v2 + v1)  # v2+v1 runs almost level, so pairs form straight rows
            for kind in "AB":
                placed.append((kind, affinity.translate(base[kind], *off)))
    return placed


def build(args):
    outline_px, lines_px, ellipses_px = read_svg(args.svg)
    s = args.scale

    def to_mm(pts):
        # SVG y grows downward; flip so the shark is the right way up in the slicer.
        return [(x * s, -y * s) for x, y in pts]

    tile0 = Polygon(to_mm(outline_px)).buffer(0)
    hx, hy = min(outline_px, key=lambda q: (q[0] - HALF_TURN_PX[0]) ** 2 + (q[1] - HALF_TURN_PX[1]) ** 2)
    center = np.array(to_mm([(hx, hy)])[0])  # midpoint of the straight edge
    rot = lambda g: affinity.rotate(g, 180, origin=tuple(center))

    # Face artwork: line strokes, eye rings, pupils.
    stroke = args.line_width
    art = [LineString(to_mm(p)).simplify(0.02).buffer(stroke / 2, cap_style=1) for p in lines_px if len(p) > 1]
    for cx, cy, rx, ry in ellipses_px:
        e = affinity.scale(Point(cx * s, -cy * s).buffer(1.0, 32), rx * s, ry * s)
        if min(rx, ry) * s < args.pupil_max:
            art.append(e)  # small ellipse: solid pupil
        else:
            art.append(e.boundary.buffer(stroke / 2))  # big ellipse: ring
    art = unary_union(art)

    # Lattice (in mm). The cell holds one tile plus its rotated partner.
    verts_px = np.array(outline_px + [(2 * hx - x, 2 * hy - y) for x, y in outline_px])
    v1 = refine_vector(verts_px, V1_APPROX) * [s, -s]
    v2 = refine_vector(verts_px, V2_APPROX) * [s, -s]
    print(f"lattice vectors (mm): v1=({v1[0]:.3f}, {v1[1]:.3f})  v2=({v2[0]:.3f}, {v2[1]:.3f})")

    if args.grid:
        ni, nj = (int(v) for v in args.grid.lower().split("x"))
        placed = place_grid(tile0, rot, v1, v2, ni, nj)
    else:
        placed = fill_rectangle(tile0, rot, v1, v2, args.area)
    if not placed:
        raise SystemExit("no whole tile fits in --area; make the area larger or the scale smaller")

    # Sanity check: neighbours must neither overlap nor leave gaps.
    total = sum(p.area for _, p in placed)
    mosaic = unary_union([p for _, p in placed])
    overlap = total - mosaic.area
    holes = sum(Polygon(r).area for g in ([mosaic] if mosaic.geom_type == "Polygon" else mosaic.geoms) for r in g.interiors)
    print(f"tiling check: tile area {tile0.area:.1f} mm2, overlap {overlap:.2f} mm2, interior gaps {holes:.2f} mm2")
    if overlap > 0.01 * total or holes > 0.01 * total:
        print("  WARNING: tiles overlap or leave gaps; lattice vectors may be wrong.")

    return dict(tile0=tile0, art=art, center=center, rot=rot, placed=placed, mosaic=mosaic, v1=v1, v2=v2)


def make_tile_mesh(nominal, art, args, kind):
    """One printable tile: flat base plus raised outline and face."""
    body = nominal.buffer(-args.gap / 2, join_style=2)
    ridge = body.difference(body.buffer(-args.ridge))
    face = art.intersection(body.buffer(-args.ridge / 2))
    raised = unary_union([ridge, face])
    return try_union(extrude(body, args.base) + extrude(raised, args.raised, z0=args.base)), body


def make_tile_parts(nominal, art, args):
    """Same tile as make_tile_mesh, but as two separate solids for two-colour printing.

    base    : flat shark shape, z = 0 .. base
    outline : raised perimeter ridge + face lines, z = base .. base+raised
    Both share one coordinate frame, so load them together as one multi-part
    object (PrusaSlicer: select both > right-click > Add part / "Assign to extruder").
    """
    body = nominal.buffer(-args.gap / 2, join_style=2)
    ridge = body.difference(body.buffer(-args.ridge))
    face = art.intersection(body.buffer(-args.ridge / 2))
    raised = unary_union([ridge, face])
    return combine(extrude(body, args.base)), combine(extrude(raised, args.raised, z0=args.base))


def make_board(g, args):
    pad = args.margin
    minx, miny, maxx, maxy = g["mosaic"].bounds
    plate = box(minx - pad, miny - pad, maxx + pad, maxy + pad)
    holes = []
    if args.push_holes:
        for _, poly in g["placed"]:
            body = poly.buffer(-args.gap / 2)
            core = body.buffer(-4)
            pt = (core if not core.is_empty else body).representative_point()
            holes.append(pt.buffer(args.push_hole_d / 2, 24))
    floor = plate.difference(unary_union(holes)) if holes else plate
    # Recess = outer outline of the whole group of sharks. Tiny interior voids between
    # tiles are filled in so no thin slivers of wall stand up inside the recess.
    parts = [g["mosaic"]] if g["mosaic"].geom_type == "Polygon" else list(g["mosaic"].geoms)
    recess = unary_union([Polygon(p.exterior) for p in parts])
    wall = plate.difference(recess)
    return try_union(extrude(floor, args.floor) + extrude(wall, args.base, z0=args.floor)), plate


def shelf_pack(items, bed_w, spacing=4.0):
    """Place identical bounding boxes in rows; returns (x, y) offsets and total height."""
    x = y = row_h = 0.0
    out = []
    for w, h in items:
        if x + w > bed_w and x > 0:
            x, y, row_h = 0.0, y + row_h + spacing, 0.0
        out.append((x, y))
        x += w + spacing
        row_h = max(row_h, h)
    return out, y + row_h


def make_plate(tile_mesh, n, bed_w):
    b = tile_mesh.bounds
    w, h = b[1][0] - b[0][0], b[1][1] - b[0][1]
    spots, total_h = shelf_pack([(w, h)] * n, bed_w)
    meshes = []
    for sx, sy in spots:
        m = tile_mesh.copy()
        m.apply_translation([sx - b[0][0], sy - b[0][1], 0])
        meshes.append(m)
    return combine(meshes), (max(x for x, _ in spots) + w, total_h)


def make_qr(args):
    qr = segno.make(args.url, error=args.qr_error, micro=False)
    mat = np.array(qr.matrix, dtype=bool)  # True = dark module
    n = mat.shape[0]
    q = args.qr_quiet
    mod = args.qr_module
    size = (n + 2 * q) * mod
    dark = []
    for r in range(n):
        for c in range(n):
            if mat[r, c]:
                x0 = (c + q) * mod
                y0 = (n - 1 - r + q) * mod  # image rows run top-down; STL y runs up
                dark.append(box(x0, y0, x0 + mod, y0 + mod).buffer(0.03, join_style=2))
    modules = unary_union(dark)
    plate = box(0, 0, size, size)
    mesh = try_union(extrude(plate, args.qr_base) + extrude(modules, args.qr_raise, z0=args.qr_base))
    print(f"  QR: {n}x{n} modules (version {qr.version}), plaque {size:.1f} mm square, module {mod} mm")
    return mesh


def _patch(ax, geom, **kw):
    from matplotlib.patches import PathPatch
    from matplotlib.path import Path as MPath
    for p in ([geom] if geom.geom_type == "Polygon" else getattr(geom, "geoms", [])):
        if p.geom_type != "Polygon" or p.is_empty:
            continue
        rings = [p.exterior] + list(p.interiors)
        verts = np.concatenate([np.array(r.coords) for r in rings])
        codes = np.concatenate([[MPath.MOVETO] + [MPath.LINETO] * (len(r.coords) - 2) + [MPath.CLOSEPOLY] for r in rings])
        ax.add_patch(PathPatch(MPath(verts, codes), **kw))


OUTLINE_COLOR = "#d62728"


def render_preview(g, plate, path, args=None):
    fig, ax = plt.subplots(figsize=(10, 7))
    colors = {"A": "#f6b73c", "B": "#4aa3df"}
    t0 = g["tile0"].bounds[:2]
    for kind, poly in g["placed"]:
        gap = args.gap if args else 0.4
        ridge_w = args.ridge if args else 1.2
        body = poly.buffer(-gap / 2, join_style=2)
        _patch(ax, poly, fc=colors[kind], ec="none", lw=0)
        _patch(ax, body.difference(body.buffer(-ridge_w)), fc=OUTLINE_COLOR, lw=0)
        ref = g["rot"](g["tile0"]) if kind == "B" else g["tile0"]
        off = np.array(poly.bounds[:2]) - np.array(ref.bounds[:2])
        art = g["rot"](g["art"]) if kind == "B" else g["art"]
        _patch(ax, affinity.translate(art, *off).intersection(body.buffer(-ridge_w / 2)), fc=OUTLINE_COLOR, lw=0)
    px, py = plate.exterior.xy
    ax.plot(px, py, "k-", lw=1)
    ax.autoscale_view()
    ax.set_aspect("equal")
    ax.set_title("Assembled puzzle: gold / blue = shark bases, red = raised outline + face (print in a 2nd colour)")
    fig.savefig(path, dpi=110, bbox_inches="tight")


# ----------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--svg", default=HERE / "BabyShark8.svg")
    ap.add_argument("--out", default=HERE / "stl")
    ap.add_argument("--scale", type=float, default=0.20, help="mm per SVG pixel (0.20 -> tile about 62 mm wide)")
    ap.add_argument("--grid", default="3x3",
                    help="lattice cells across x down; each cell is 2 sharks, so 3x3 = 18 sharks. "
                         "Use 'none' to fill --area instead")
    ap.add_argument("--area", default="200x150", help="WxH box (mm) the puzzle is cut to; only whole tiles inside it are used")
    ap.add_argument("--gap", type=float, default=0.4, help="clearance between neighbouring tiles (mm)")
    ap.add_argument("--base", type=float, default=3.0, help="tile thickness (mm)")
    ap.add_argument("--raised", type=float, default=1.5, help="raised outline/face height (mm)")
    ap.add_argument("--ridge", type=float, default=1.2, help="raised outline width (mm)")
    ap.add_argument("--line-width", type=float, default=0.9, help="face line width (mm)")
    ap.add_argument("--pupil-max", type=float, default=2.2, help="ellipses smaller than this radius (mm) are solid")
    ap.add_argument("--floor", type=float, default=2.0, help="board floor thickness (mm)")
    ap.add_argument("--margin", type=float, default=9.0, help="board border around the puzzle (mm)")
    ap.add_argument("--push-holes", action=argparse.BooleanOptionalAction, default=False,
                    help="hole under each tile so it can be pushed out from below")
    ap.add_argument("--push-hole-d", type=float, default=8.0)
    ap.add_argument("--bed", type=float, default=220.0, help="print bed width used to arrange tile plates (mm)")
    ap.add_argument("--url", default="https://something.us.com", help="address the QR code opens")
    ap.add_argument("--qr-error", default="m", choices=list("lmqh"))
    ap.add_argument("--qr-module", type=float, default=1.6, help="QR square size (mm); keep a multiple of the nozzle")
    ap.add_argument("--qr-quiet", type=int, default=4, help="blank border, in modules")
    ap.add_argument("--qr-base", type=float, default=2.0)
    ap.add_argument("--qr-raise", type=float, default=1.0)
    args = ap.parse_args()
    if args.grid.lower() == "none":
        args.grid = None
    args.area = tuple(float(v) for v in args.area.lower().split("x"))
    out = Path(args.out)

    g = build(args)
    print("writing STL files:")
    tile_a, _ = make_tile_mesh(g["placed"][0][1], g["art"], args, "A")
    save(tile_a, out / "tile.stl")
    na = sum(1 for k, _ in g["placed"] if k == "A")
    nb = len(g["placed"]) - na
    print(f"puzzle: {na + nb} sharks ({na} upright + {nb} upside-down)")
    base_m, outline_m = make_tile_parts(g["placed"][0][1], g["art"], args)
    save(base_m, out / "tile_base.stl")
    save(outline_m, out / "tile_outline.stl")
    plate_a, _ = make_plate(tile_a, na, args.bed)
    save(plate_a, out / "tiles_color_A.stl")
    if nb:
        plate_b, _ = make_plate(tile_a, nb, args.bed)  # partners are the same shape, turned 180 degrees
        save(plate_b, out / "tiles_color_B.stl")
    # Two-colour plates: identical layout, split into base + outline solids.
    for name, n in (("A", na), ("B", nb)):
        if n:
            pb, _ = make_plate(base_m, n, args.bed)
            po, _ = make_plate(outline_m, n, args.bed)
            save(pb, out / f"tiles_color_{name}_base.stl")
            save(po, out / f"tiles_color_{name}_outline.stl")
    board, plate = make_board(g, args)
    save(board, out / "board.stl")
    save(make_qr(args), out / "qr_plaque.stl")
    render_preview(g, plate, out / "preview.png", args)
    if "something.us.com" in args.url:
        print("NOTE: QR code uses the placeholder URL; rerun with --url once the website address is final.")


if __name__ == "__main__":
    main()
