#!/usr/bin/env python3
"""Tile a drilling template exported from OpenSCAD onto printable pages.

Reads the SVG export of the template part of main.scad and writes a PDF at
1:1 scale, split over pages of the chosen paper size. Neighbouring pages
overlap. A dashed line runs through the middle of each overlap, with
crosses every 50 mm along it: trim one sheet along the line, lay it over
its neighbour so line and crosses match, and tape it. Each page names its
row and column.

Print at 100% (actual size) and check the 100 mm scale bar.

Only the Python standard library is used. The SVG must consist of path
elements with straight segments (M, L and z commands), which is what
OpenSCAD exports for 2D shapes.
"""

import argparse
import math
import os
import re
import sys
import xml.etree.ElementTree as ET

MM = 72 / 25.4   # PDF points per mm
PAPER = {"a4": (210, 297), "a3": (297, 420), "letter": (215.9, 279.4),
         "legal": (215.9, 355.6)}


def parse_args():
    """Parse the command line."""
    p = argparse.ArgumentParser(description=__doc__,
                                formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("svg", help="SVG export of the template part")
    p.add_argument("-o", "--output", help="output PDF (default: the SVG name with .pdf)")
    p.add_argument("--paper", choices=sorted(PAPER), default="a4",
                   help="paper size (default: %(default)s)")
    p.add_argument("--margin", type=float, default=6,
                   help="unprintable margin along the paper edges in mm (default: %(default)s)")
    p.add_argument("--overlap", type=float, default=10,
                   help="overlap between neighbouring pages in mm (default: %(default)s)")
    p.add_argument("--line", type=float, default=.2,
                   help="line width in mm (default: %(default)s)")
    return p.parse_args()


def read_svg(path):
    """Read the polygons of an OpenSCAD SVG export.

    Returns:
        (polygons, width, height): polygons as lists of (x, y) in mm with
        the origin at the lower left corner of the drawing and y up, and the
        drawing size in mm.

    Raises:
        SystemExit: the file contains elements or path commands other than
            those OpenSCAD writes for 2D shapes, or its units are not mm.
    """
    root = ET.parse(path).getroot()
    ns = "{http://www.w3.org/2000/svg}"
    vb = [float(v) for v in root.get("viewBox", "").replace(",", " ").split()]
    if len(vb) != 4:
        sys.exit(f"{path}: no viewBox")
    minx, miny, w, h = vb
    width = root.get("width", "")
    if not width.endswith("mm") or not math.isclose(float(width[:-2]), w, rel_tol=1e-6):
        sys.exit(f"{path}: width {width!r} does not match the viewBox in mm")
    polygons = []
    for el in root.iter():
        tag = el.tag.replace(ns, "")
        if tag in ("svg", "title"):
            continue
        if tag != "path":
            sys.exit(f"{path}: unexpected element {tag!r}")
        tokens = re.findall(r"[A-Za-z]|-?[\d.]+(?:[eE][-+]?\d+)?", el.get("d", ""))
        cur, i = None, 0
        while i < len(tokens):
            t = tokens[i]
            if t in ("M", "L"):
                x, y = float(tokens[i + 1]), float(tokens[i + 2])
                pt = (x - minx, miny + h - y)
                if t == "M":
                    cur = [pt]
                    polygons.append(cur)
                else:
                    cur.append(pt)
                i += 3
            elif t in ("z", "Z"):
                i += 1
            else:
                sys.exit(f"{path}: unexpected path data {t!r}")
    return polygons, w, h


def tiles(total, page, overlap):
    """Start positions of pages covering a length.

    Args:
        total: length of the drawing.
        page: printable length of a page.
        overlap: overlap between neighbouring pages.

    Returns:
        list of start positions, the first at 0.
    """
    step = page - overlap
    n = max(1, math.ceil((total - overlap) / step))
    return [i * step for i in range(n)]


def layout(w, h, args):
    """Choose portrait or landscape pages, whichever needs fewer.

    Returns:
        (paper width, paper height, x starts, y starts) in mm.
    """
    best = None
    for pw, ph in (PAPER[args.paper], PAPER[args.paper][::-1]):
        xs = tiles(w, pw - 2 * args.margin, args.overlap)
        ys = tiles(h, ph - 2 * args.margin, args.overlap)
        if best is None or len(xs) * len(ys) < len(best[2]) * len(best[3]):
            best = (pw, ph, xs, ys)
    return best


def fmt(v):
    """Number for a PDF content stream."""
    return f"{v:.3f}".rstrip("0").rstrip(".")


def page_content(polygons, x0, y0, pw, ph, w, h, cuts_x, cuts_y, label, args):
    """Content stream of one page.

    The drawing is shifted so that (x0, y0) lies at the lower left corner of
    the printable area, and clipped to that area.

    Args:
        polygons, w, h: the drawing, see read_svg().
        x0, y0: drawing position at the lower left of the printable area.
        pw, ph: paper size in mm.
        cuts_x, cuts_y: positions of the trim lines in the drawing.
        label: page name for the bottom margin.
        args: command line arguments.
    """
    m = args.margin
    out = [f"q {fmt(m * MM)} {fmt(m * MM)} {fmt((pw - 2 * m) * MM)} {fmt((ph - 2 * m) * MM)} "
           f"re W n",
           f"1 0 0 1 {fmt((m - x0) * MM)} {fmt((m - y0) * MM)} cm",
           f"{fmt(args.line * MM)} w 1 j 1 J 0 G"]
    for poly in polygons:
        out.append(f"{fmt(poly[0][0] * MM)} {fmt(poly[0][1] * MM)} m " +
                   " ".join(f"{fmt(x * MM)} {fmt(y * MM)} l" for x, y in poly[1:]) + " h S")
    # guides: dashed trim lines through the overlaps, crosses every 50 mm
    out.append(f"0.6 G {fmt(.15 * MM)} w")
    out.append(f"[{fmt(3 * MM)} {fmt(2 * MM)}] 0 d")
    for x in cuts_x:
        out.append(f"{fmt(x * MM)} 0 m {fmt(x * MM)} {fmt(h * MM)} l S")
    for y in cuts_y:
        out.append(f"0 {fmt(y * MM)} m {fmt(w * MM)} {fmt(y * MM)} l S")
    out.append("[] 0 d")
    c = 3   # half cross size
    for x in cuts_x:
        for y in range(0, int(h) + 1, 50):
            out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
                       f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
    for y in cuts_y:
        for x in range(0, int(w) + 1, 50):
            out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
                       f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
    out.append("Q")
    # page name in the bottom margin
    out.append(f"BT /F1 7 Tf 0 g {fmt(m * MM)} {fmt(m / 2 * MM)} Td "
               f"({label}, print at 100%) Tj ET")
    return "\n".join(out).encode("ascii")


def write_pdf(path, pages, pw, ph):
    """Write a PDF with one page per content stream.

    Args:
        path: output file.
        pages: list of content streams (bytes).
        pw, ph: page size in mm.
    """
    n = len(pages)
    # objects: 1 catalog, 2 page tree, 3 font, then page and content per page
    objs = [b"<< /Type /Catalog /Pages 2 0 R >>",
            ("<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(n))
             + f"] /Count {n} >>").encode(),
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
    for i, content in enumerate(pages):
        objs.append((f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {fmt(pw * MM)} "
                     f"{fmt(ph * MM)}] /Resources << /Font << /F1 3 0 R >> >> "
                     f"/Contents {5 + 2 * i} 0 R >>").encode())
        objs.append(f"<< /Length {len(content)} >>\nstream\n".encode() + content
                    + b"\nendstream")
    data = bytearray(b"%PDF-1.4\n")
    offsets = []
    for i, obj in enumerate(objs):
        offsets.append(len(data))
        data += f"{i + 1} 0 obj\n".encode() + obj + b"\nendobj\n"
    xref = len(data)
    data += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
    for off in offsets:
        data += f"{off:010d} 00000 n \n".encode()
    data += (f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\n"
             f"startxref\n{xref}\n%%EOF\n").encode()
    with open(path, "wb") as f:
        f.write(data)


def main():
    """Read the SVG, lay out the pages and write the PDF."""
    args = parse_args()
    polygons, w, h = read_svg(args.svg)
    pw, ph, xs, ys = layout(w, h, args)
    tile_h = ph - 2 * args.margin
    ov = args.overlap
    # ys count from the top of the drawing, so the pages come in reading order
    cuts_x = [x + ov / 2 for x in xs[1:]]
    cuts_y = [h - y - ov / 2 for y in ys[1:]]
    pages = []
    for row, y in enumerate(ys):
        for col, x0 in enumerate(xs):
            label = f"row {row + 1} of {len(ys)}, column {col + 1} of {len(xs)}"
            pages.append(page_content(polygons, x0, h - y - tile_h, pw, ph, w, h,
                                      cuts_x, cuts_y, label, args))
    out = args.output or os.path.splitext(args.svg)[0] + ".pdf"
    write_pdf(out, pages, pw, ph)
    orient = "portrait" if pw < ph else "landscape"
    print(f"{w:.0f} x {h:.0f} mm on {len(pages)} {args.paper} pages, {orient}, "
          f"{len(ys)} rows of {len(xs)}: {out}")


if __name__ == "__main__":
    main()
