"""Simple 3 colour test shapes for the pancake printer.

Each shape is filled with concentric loops spaced well apart:
  outermost loop      -> dark batter   (syringe 0, line art)
  middle loops        -> medium batter (syringe 1)
  inner loops         -> light batter  (syringe 2)

The first loop sits half a bead inside the shape edge, so the printed edge is the
shape edge. Every further loop is PITCH further in. Only plain stroked paths are
written (fill="none"), in mm, in the exact nozzle colours of pancake_config.yaml,
so the team's colors.py maps every colour to its own syringe.

Usage: python make_test_shapes.py [--pitch 10] [--bead 4] [--out .]
Needs numpy, shapely and matplotlib (only for the preview).
"""
import argparse
import math
from pathlib import Path

import numpy as np
from shapely.geometry import Point, Polygon
from shapely.geometry.polygon import orient

BATTER_COLOURS = {0: "#5a3216", 1: "#b07a3a", 2: "#e8c27a"}   # dark, medium, light (nozzle colours)
MARGIN_MM = 5.0
MIN_LOOP_LENGTH_MM = 8.0


# --------------------------------------------------------------------------- shapes (mm, centred on 0,0, y down)


def circle(diameter=110):
    return Point(0, 0).buffer(diameter / 2, quad_segs=64)


def star(outer_radius=62, inner_radius=30, points=5):
    corners = []
    for i in range(2 * points):
        radius = outer_radius if i % 2 == 0 else inner_radius
        angle = math.pi / points * i - math.pi / 2      # first tip points up
        corners.append((radius * math.cos(angle), radius * math.sin(angle)))
    return Polygon(corners)


def heart(width=115):
    t = np.linspace(0, 2 * math.pi, 400, endpoint=False)
    x = 16 * np.sin(t) ** 3
    y = -(13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t))   # y down
    scale = width / (x.max() - x.min())
    raw = Polygon(np.column_stack([x, y]) * scale)
    return raw.buffer(6).buffer(-6)     # round off the notch at the top so the loops don't fold into it


def square(side=100):
    h = side / 2
    return Polygon([(-h, -h), (h, -h), (h, h), (-h, h)])


def triangle(side=125):
    height = side * math.sqrt(3) / 2
    return Polygon([(0, -2 * height / 3), (side / 2, height / 3), (-side / 2, height / 3)])


def hexagon(diameter=115):
    r = diameter / 2
    return Polygon([(r * math.cos(math.pi / 3 * i), r * math.sin(math.pi / 3 * i)) for i in range(6)])


SHAPES = {
    "circle": (circle, "round"),
    "star": (star, "mitre"),
    "heart": (heart, "round"),
    "square": (square, "mitre"),
    "triangle": (triangle, "mitre"),
    "hexagon": (hexagon, "mitre"),
}


# --------------------------------------------------------------------------- loops and colours


def concentric_loops(shape, bead, pitch, join_style):
    """Loops at bead/2, bead/2 + pitch, ... inside the shape edge, outermost first.
    Returns a list of rings (one inset can split into several rings)."""
    rings_per_inset = []
    inset = bead / 2
    while True:
        region = shape.buffer(-inset, join_style=join_style, mitre_limit=10)
        if region.is_empty:
            break
        parts = getattr(region, "geoms", [region])
        rings = [orient(p).exterior for p in parts if p.exterior.length >= MIN_LOOP_LENGTH_MM]
        if not rings:
            break
        rings_per_inset.append(rings)
        inset += pitch
    return rings_per_inset


def colour_groups(n_insets):
    """Nozzle per inset, outside in: the loops split in thirds dark / medium / light.
    Leftover loops go to the light centre first, then medium (6 -> 2/2/2, 5 -> 1/2/2, 4 -> 1/1/2)."""
    if n_insets < 3:
        raise ValueError("shape too small for 3 colours at this pitch")
    counts = [n_insets // 3] * 3
    for i in range(n_insets % 3):
        counts[2 - i] += 1
    return [0] * counts[0] + [1] * counts[1] + [2] * counts[2]


# --------------------------------------------------------------------------- output


def write_svg(path, rings_per_inset, nozzles, shape, bead):
    minx, miny, maxx, maxy = shape.bounds
    width = maxx - minx + 2 * MARGIN_MM
    height = maxy - miny + 2 * MARGIN_MM
    dx, dy = MARGIN_MM - minx, MARGIN_MM - miny
    lines = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.2f}mm" height="{height:.2f}mm" '
        f'viewBox="0 0 {width:.3f} {height:.3f}">',
    ]
    for nozzle in (0, 1, 2):
        lines.append(f'<g id="syringe{nozzle}">')
        for rings, n in zip(rings_per_inset, nozzles):
            if n != nozzle:
                continue
            for ring in rings:
                pts = np.asarray(ring.coords)[:-1] + [dx, dy]
                d = "M " + " L ".join(f"{x:.2f} {y:.2f}" for x, y in pts) + " Z"
                lines.append(f'  <path d="{d}" fill="none" stroke="{BATTER_COLOURS[n]}" '
                             f'stroke-width="{bead:g}" stroke-linejoin="round"/>')
        lines.append("</g>")
    lines.append("</svg>")
    Path(path).write_text("\n".join(lines) + "\n", encoding="utf-8")


def line_length_per_colour(rings_per_inset, nozzles):
    total = {0: 0.0, 1: 0.0, 2: 0.0}
    for rings, n in zip(rings_per_inset, nozzles):
        total[n] += sum(r.length for r in rings)
    return total


def save_preview(path, designs, bead, pitch):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(2, 3, figsize=(12, 8.4), facecolor="white")
    for ax, (name, shape, rings_per_inset, nozzles) in zip(axes.flat, designs):
        ax.set_facecolor("#f6efe4")
        ax.set_aspect("equal")
        lim = 70
        ax.set_xlim(-lim, lim)
        ax.set_ylim(lim, -lim)                       # y down like the SVG
        pts_per_mm = ax.get_window_extent().width / (2 * lim) * 72 / fig.dpi
        ax.plot(*np.asarray(shape.exterior.coords).T, color="0.6", lw=0.6, ls="--")
        for rings, n in zip(rings_per_inset, nozzles):
            for ring in rings:
                ax.plot(*np.asarray(ring.coords).T, color=BATTER_COLOURS[n],
                        lw=bead * pts_per_mm, solid_capstyle="round", solid_joinstyle="round")
        lengths = line_length_per_colour(rings_per_inset, nozzles)
        ax.set_title(f"{name}: {lengths[0]:.0f} / {lengths[1]:.0f} / {lengths[2]:.0f} mm", fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
    fig.suptitle(f"Test shapes, bead {bead:g} mm, pitch {pitch:g} mm (line length dark / medium / light). "
                 "Dashed: shape edge", fontsize=11)
    fig.tight_layout()
    fig.savefig(path, dpi=110)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--bead", type=float, default=4.0, help="line width in mm (print.line_width)")
    parser.add_argument("--pitch", type=float, default=10.0, help="centre to centre spacing of the loops in mm")
    parser.add_argument("--out", type=Path, default=Path(__file__).parent)
    args = parser.parse_args()

    args.out.mkdir(parents=True, exist_ok=True)
    designs = []
    for name, (make_shape, join_style) in SHAPES.items():
        shape = make_shape()
        rings_per_inset = concentric_loops(shape, args.bead, args.pitch, join_style)
        nozzles = colour_groups(len(rings_per_inset))
        write_svg(args.out / f"shape_{name}.svg", rings_per_inset, nozzles, shape, args.bead)
        designs.append((name, shape, rings_per_inset, nozzles))
        minx, miny, maxx, maxy = shape.bounds
        print(f"{name:9s} {maxx - minx:5.0f} x {maxy - miny:4.0f} mm, loops per colour "
              f"{nozzles.count(0)}/{nozzles.count(1)}/{nozzles.count(2)}")
    save_preview(args.out / "shapes_preview.png", designs, args.bead, args.pitch)


if __name__ == "__main__":
    main()
