"""HTMAA text as a 3 colour pancake toolpath.

  dark   (syringe 0): the letters, as single lines (printed first, so they end up
                      on top of the pancake after flipping)
  medium (syringe 1): one frame loop around the text
  light  (syringe 2): one zigzag fill inside the frame, PITCH apart, printed over
                      the letters so letters and frame end up as one pancake

The pancake is flipped, so the default output is mirrored: it reads correctly
after flipping. --readable writes the unmirrored version as well.

Usage: python make_htmaa_text.py [--text HTMAA] [--height 30] [--pitch 10] [--bead 4] [--readable]
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 LineString, box

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


# --------------------------------------------------------------------------- letters (y down, top left = 0,0)


def letter_strokes(char, h):
    """Single line strokes of one block letter of height h. Returns (strokes, width)."""
    if char == "H":
        w = 0.67 * h
        return [[(0, 0), (0, h)], [(w, 0), (w, h)], [(0, h / 2), (w, h / 2)]], w
    if char == "T":
        w = 0.73 * h
        return [[(0, 0), (w, 0)], [(w / 2, 0), (w / 2, h)]], w
    if char == "M":
        w = 0.87 * h
        return [[(0, h), (0, 0), (w / 2, 0.6 * h), (w, 0), (w, h)]], w
    if char == "A":
        w = 0.8 * h
        bar_y = 0.62 * h
        bar_x = w / 2 * (h - bar_y) / h        # where the bar meets the left leg
        return [[(0, h), (w / 2, 0), (w, h)], [(bar_x, bar_y), (w - bar_x, bar_y)]], w
    raise ValueError(f"no strokes defined for '{char}' (only H, T, M, A)")


def text_strokes(text, h, letter_gap):
    strokes, x = [], 0.0
    for char in text:
        char_strokes, w = letter_strokes(char, h)
        strokes += [[(px + x, py) for px, py in s] for s in char_strokes]
        x += w + letter_gap
    return strokes, x - letter_gap


# --------------------------------------------------------------------------- frame and fill


def rounded_plate(width, height, radius):
    return box(radius, radius, width - radius, height - radius).buffer(radius, quad_segs=16)


def zigzag_fill(region, pitch):
    """Horizontal lines at most `pitch` apart over the region, joined at alternating ends into one stroke."""
    minx, miny, maxx, maxy = region.bounds
    n_lines = math.ceil((maxy - miny) / pitch) + 1
    points = []
    for i, y in enumerate(np.linspace(miny + 0.5, maxy - 0.5, n_lines)):
        cut = region.intersection(LineString([(minx - 1, y), (maxx + 1, y)]))
        x0, _, x1, _ = cut.bounds
        points += [(x0, y), (x1, y)] if i % 2 == 0 else [(x1, y), (x0, y)]
    return points


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


def build_layers(args):
    letter_gap = 0.3 * args.height
    strokes, text_width = text_strokes(args.text, args.height, letter_gap)
    pad = args.bead / 2 + args.pitch                      # frame centre line to letter centre lines
    plate_w, plate_h = text_width + 2 * (pad + args.bead / 2), args.height + 2 * (pad + args.bead / 2)
    plate = rounded_plate(plate_w, plate_h, radius=min(plate_h / 2, 15))
    offset = pad + args.bead / 2
    letters = [[(x + offset, y + offset) for x, y in s] for s in strokes]
    frame = list(plate.buffer(-args.bead / 2).exterior.coords)[:-1]
    inset = args.bead / 2 + args.pitch                    # straight ends: the fill area is the plate's
    fill = zigzag_fill(box(inset, inset, plate_w - inset, plate_h - inset), args.pitch)   # box, not its rounded outline
    layers = {0: [(p, False) for p in letters], 1: [(frame, True)], 2: [(fill, False)]}
    return layers, plate_w, plate_h


def mirrored(layers, width):
    return {n: [([(width - x, y) for x, y in pts], closed) for pts, closed in paths] for n, paths in layers.items()}


def write_svg(path, layers, w, h, bead):
    lines = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{w + 2 * MARGIN_MM:.2f}mm" '
        f'height="{h + 2 * MARGIN_MM:.2f}mm" viewBox="0 0 {w + 2 * MARGIN_MM:.3f} {h + 2 * MARGIN_MM:.3f}">',
    ]
    for nozzle, paths in layers.items():
        lines.append(f'<g id="syringe{nozzle}">')
        for pts, closed in paths:
            d = "M " + " L ".join(f"{x + MARGIN_MM:.2f} {y + MARGIN_MM:.2f}" for x, y in pts) + (" Z" if closed else "")
            lines.append(f'  <path d="{d}" fill="none" stroke="{BATTER_COLOURS[nozzle]}" stroke-width="{bead:g}" '
                         'stroke-linecap="round" stroke-linejoin="round"/>')
        lines.append("</g>")
    lines.append("</svg>")
    Path(path).write_text("\n".join(lines) + "\n", encoding="utf-8")


def save_preview(path, printed, after_flip, w, h, bead, pitch):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(2, 1, figsize=(10, 7.2), facecolor="white")
    panels = [(printed, "As printed on the griddle (mirrored)"),
              (after_flip, "After flipping: dark lines on top, light and medium batter underneath")]
    for ax, (layers, title) in zip(axes, panels):
        ax.set_facecolor("#f6efe4")
        ax.set_aspect("equal")
        ax.set_xlim(-8, w + 8)
        ax.set_ylim(h + 8, -8)
        pts_per_mm = ax.get_window_extent().width / (w + 16) * 72 / fig.dpi
        order = (0, 1, 2) if layers is printed else (2, 1, 0)   # what ends up on top in each view
        for nozzle in order:
            for pts, closed in layers[nozzle]:
                xy = np.asarray(pts + pts[:1] if closed else pts)
                ax.plot(*xy.T, color=BATTER_COLOURS[nozzle], lw=bead * pts_per_mm,
                        solid_capstyle="round", solid_joinstyle="round")
        ax.set_title(title, fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
    fig.suptitle(f"{w:.0f} x {h:.0f} mm, bead {bead:g} mm, fill pitch {pitch:g} mm", 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("--text", default="HTMAA", help="letters H, T, M and A only")
    parser.add_argument("--height", type=float, default=30.0, help="letter height in mm")
    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="fill line spacing and text to frame gap in mm")
    parser.add_argument("--readable", action="store_true", help="also write the unmirrored version")
    parser.add_argument("--out", type=Path, default=Path(__file__).parent)
    args = parser.parse_args()

    layers, w, h = build_layers(args)
    printed = mirrored(layers, w)
    name = f"text_{args.text}"
    write_svg(args.out / f"{name}.svg", printed, w, h, args.bead)
    if args.readable:
        write_svg(args.out / f"{name}_unmirrored.svg", layers, w, h, args.bead)
    save_preview(args.out / f"{name}_preview.png", printed, layers, w, h, args.bead, args.pitch)
    lengths = {n: sum(LineString(p + p[:1] if c else p).length for p, c in paths) for n, paths in layers.items()}
    print(f"{name}: {w:.0f} x {h:.0f} mm, line length dark/medium/light "
          f"{lengths[0]:.0f}/{lengths[1]:.0f}/{lengths[2]:.0f} mm")


if __name__ == "__main__":
    main()
