#!/usr/bin/env python3
"""Export the handwriting of a .noteful notebook as SVG: one file per page, centreline strokes.

    python examples/svg_export.py notebook.noteful                    # every page -> notebook-svg/
    python examples/svg_export.py notebook.noteful --page 2 -o p2.svg
    python examples/svg_export.py notebook.noteful --prefix talk/panel   # talk/panel-p1.svg, -p2.svg, ...
    python examples/svg_export.py notebook.noteful --background embed --simplify 0.3 --smooth

Centreline, not outline
-----------------------
Every stroke is a ``<path>`` along the pen's centreline with ``fill="none"``, a ``stroke`` colour,
a ``stroke-width`` and round caps / joins, instead of a filled polygon around the ink. The line
width stays an attribute you can change, and plotters, laser cutters, Inkscape's "stroke to path"
and CSS / SMIL animation can all follow the path.

Pressure. Noteful draws a pressure pen about 2.1 x pressure thick *per point*; a path has one
width. ``--pressure variable`` (default) cuts a stroke wherever the pressure moves by more than
``--width-step`` page units and gives each piece its mean width; ``--pressure uniform`` keeps one
path per stroke at its mean width. Strokes without pressure (fineliner, highlighter, shapes) are
always a single constant-width path.

``--order time`` writes the strokes into one ``<g id="ink">`` in the order they were written
(``data-t``, then stream position), so the file reads in drawing order and a script can walk it
top to bottom; there is no ``<g id="highlighter">`` then. Highlighter strokes are grouped in runs
(``<g class="hl-run">``) with ``mix-blend-mode: multiply`` and the highlighter opacity, which keeps
dark ink dark under them but is not identical to drawing them under the ink: coloured ink beneath a
highlight is tinted, and highlights separated by ink that overlap one another darken.

Layout of the file (the same layering as ``noteful_mcp.notebook`` renders)::

    <g id="highlighter" opacity="0.42">   all highlighter strokes, under the ink; overlaps of
                                          the group do not darken, as in the app
    <g id="ink">                          pen strokes (and ruler lines / auto-shapes), file order
    <g id="tape">                         tape, on top: striped when covering, outline when revealed

Each stroke has ``id="s0001"`` (its position in the file's stroke stream, which is also its
z-order), a ``class`` of ``pen`` / ``hl`` (plus ``shape`` for shape elements) and ``data-t``, the
seconds between the page's first stroke and this one (what examples/noteful-draw.js replays; it is
0 for every stroke of a notebook whose strokes all share one clock). Every path also has
``data-length``, its length in page units, measured on the coordinates as written in ``d``; a stroke
cut into several pieces (``<g>``) carries the total. That is what a dash-offset or SMIL animation
needs to draw the stroke on at a steady pen speed without measuring anything. With ``--smooth``
the paths are Bezier curves and carry no ``data-length``. Pixel-erased parts are cut out, each
visible run its own path; fully erased strokes are left out.

Tape is the one thing that is not a plain centreline: covered tape is a stroke painted with a
striped ``<pattern>``, and revealed tape (shown as an outline in the app) is a stroke clipped by a
``<mask>``. Browsers and resvg draw both correctly; a renderer without mask support (CairoSVG, for
one) shows revealed tape as a solid band. ``--no-tape`` leaves tape out, which is also what you
want for plotting or cutting.

Coordinates are Noteful page units (the ``viewBox``); ``--scale`` only sets the ``width`` /
``height`` attributes.

Background. ``--background none`` (default) is transparent and pure vector; a colour name or
``#rrggbb`` (``black``, ``white``, ...) adds a solid rectangle of that colour, which light ink on a
dark page needs; ``embed`` rasterises the paper / PDF background *and the page's image elements* into
an embedded PNG. Without ``embed`` those are not in the SVG. Text boxes and stickers are not
rendered by noteful_mcp at all, so they are not here either.

Needs the repo's own dependencies (pillow, pymupdf).
"""

from __future__ import annotations

import argparse
import base64
import io
import itertools
import math
import sys
from pathlib import Path
from xml.sax.saxutils import escape

try:
    from noteful_mcp import ink
except ImportError:  # running from a source checkout that is not installed
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
    from noteful_mcp import ink

from PIL import ImageColor

from noteful_mcp.notebook import HIGHLIGHT_ALPHA, TAPE_STRIPE, Notebook, Page, Tape

EDGE = 1.0  # outline thickness of revealed tape, page units
LOOK = 'fill="none" stroke-linecap="round" stroke-linejoin="round"'  # shared by every stroke group


# ------------------------------------------------------------------------------- formatting
def num(v: float, prec: int) -> str:
    s = f"{v:.{prec}f}"
    if "." in s:
        s = s.rstrip("0").rstrip(".")
    return "0" if s in ("", "-0") else s


def hexcol(c) -> str:
    return "#{:02x}{:02x}{:02x}".format(*(max(0, min(255, round(v * 255))) for v in c[:3]))


def attrs(d: dict) -> str:
    out = []
    for k, v in d.items():
        if v is None:
            continue
        k = "xlink:href" if k == "xlink_href" else k.rstrip("_").replace("_", "-")
        out.append(f'{k}="{v}"')
    return " ".join(out)


def el(name: str, **a) -> str:
    return f"<{name} {attrs(a)}/>"


# ------------------------------------------------------------------------------- geometry
def point_width(s: ink.Stroke, p: float) -> float:
    """Thickness at one point, as Noteful draws it (see notebook._ink_layer)."""
    return max(0.5, 2.1 * p) if s.tool & ink.F_PRESSURE else 2 * s.width


def dedupe(pts: list, eps: float) -> list:
    out = [pts[0]] if pts else []
    for q in pts[1:]:
        if math.dist(q[:2], out[-1][:2]) > eps:
            out.append(q)
    return out


def rdp(pts: list, eps: float) -> list:
    """Ramer-Douglas-Peucker on x, y (iterative, so long strokes cannot hit the recursion limit)."""
    n = len(pts)
    if n < 3 or eps <= 0:
        return pts
    keep = [False] * n
    keep[0] = keep[-1] = True
    stack = [(0, n - 1)]
    while stack:
        a, b = stack.pop()
        ax, ay = pts[a][:2]
        bx, by = pts[b][:2]
        dx, dy = bx - ax, by - ay
        ln = math.hypot(dx, dy)
        dmax, idx = -1.0, -1
        for i in range(a + 1, b):
            px, py = pts[i][:2]
            d = abs(dx * (ay - py) - dy * (ax - px)) / ln if ln > 0 else math.hypot(px - ax, py - ay)
            if d > dmax:
                dmax, idx = d, i
        if dmax > eps:
            keep[idx] = True
            stack += [(a, idx), (idx, b)]
    return [p for p, k in zip(pts, keep) if k]


def split_by_width(s: ink.Stroke, pts: list, step: float) -> list[tuple[float, list]]:
    """Cut a polyline where its pressure width drifts by >= step; each piece gets its mean width.

    Neighbouring pieces share their boundary point, so the stroke stays connected."""
    ws = [point_width(s, p[2]) for p in pts]
    if len(pts) == 1:
        return [(ws[0], pts)]
    cuts, start, cur = [], 0, ws[0]
    for i in range(1, len(pts)):
        if abs(ws[i] - cur) >= step:
            cuts.append((start, i))
            start, cur = i, ws[i]
    last = len(pts) - 1
    if start < last or not cuts:
        cuts.append((start, last))
    return [(sum(ws[a : b + 1]) / (b - a + 1), pts[a : b + 1]) for a, b in cuts]


def path_d(pts: list, o) -> str:
    f = lambda v: num(v, o.precision)  # noqa: E731
    d = [f"M{f(pts[0][0])} {f(pts[0][1])}"]
    if not o.smooth or len(pts) < 3:
        d.append("L" + " ".join(f"{f(x)} {f(y)}" for x, y, *_ in pts[1:]))
        return "".join(d)
    n, segs = len(pts), []
    for i in range(n - 1):  # Catmull-Rom through the points, as cubic Beziers
        p0, p1, p2, p3 = pts[max(i - 1, 0)], pts[i], pts[i + 1], pts[min(i + 2, n - 1)]
        c1 = (p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6)
        c2 = (p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6)
        segs.append(" ".join(f(v) for v in (*c1, *c2, p2[0], p2[1])))
    d.append("C" + " ".join(segs))
    return "".join(d)


# ----------------------------------------------------------------------------- stroke -> svg
def pieces_for(s: ink.Stroke, runs: list, o) -> list[tuple[float, list]]:
    """[(width, points)] for the visible runs of a stroke, after de-duplication and simplifying."""
    eps = 0.5 * 10**-o.precision
    runs = [r for r in (dedupe(r, eps) for r in runs) if r]
    if not runs:
        return []
    if not (s.tool & ink.F_PRESSURE) or o.pressure == "uniform":
        allw = [point_width(s, p[2]) for r in runs for p in r]
        w = sum(allw) / len(allw)
        out = [(w, r) for r in runs]
    else:
        out = [piece for r in runs for piece in split_by_width(s, r, o.width_step)]
    return [(w, rdp(r, o.simplify)) for w, r in out]


def polyline_length(pts: list, prec: int) -> float:
    """Length of the polyline the path ``M p0 L p1 p2 ...`` draws, on the coordinates as written."""
    xy = [(float(f"{p[0]:.{prec}f}"), float(f"{p[1]:.{prec}f}")) for p in pts]
    return sum(math.dist(a, b) for a, b in itertools.pairwise(xy))


def draw(pieces: list[tuple[float, list]], paint: str, o) -> list[tuple[str, dict]]:
    """One element per piece, in drawing order: a path, or a dot (circle) for a single-point run.

    Pieces are never merged into one multi-subpath path: a dash pattern restarts on every subpath,
    so a script drawing the stroke on would draw the pieces all at once instead of one after the other."""
    out: list[tuple[str, dict]] = []
    for w, pts in pieces:
        if len(pts) == 1:
            x, y = pts[0][:2]
            out.append(
                ("circle", dict(cx=num(x, o.precision), cy=num(y, o.precision), r=num(w / 2, 3), fill=paint))
            )
        else:
            a = dict(d=path_d(pts, o), stroke=paint, stroke_width=num(w, 3))
            if not (o.smooth and len(pts) >= 3):  # a polyline, so its length is a plain sum
                a["data_length"] = num(polyline_length(pts, o.precision), 2)
            out.append(("path", a))
    return out


def emit(items: list[tuple[str, dict]], common: dict) -> str:
    """One element carries the common attributes itself; several are wrapped in a <g>."""
    if len(items) == 1:
        name, a = items[0]
        return el(name, **{**common, **a})
    lengths = [a.get("data_length") for _, a in items if a.get("data_length") is not None]
    if lengths and len(lengths) == sum(nm == "path" for nm, _ in items):  # circles have no length
        common = {**common, "data_length": num(sum(float(v) for v in lengths), 2)}
    return f"<g {attrs(common)}>" + "".join(el(nm, **a) for nm, a in items) + "</g>"


# --------------------------------------------------------------------------------- tape
def tape_pattern(col: str, rgb) -> str:
    """Diagonal stripes like notebook.draw_tapes: light ground, stripes TAPE_STRIPE apart."""
    period = TAPE_STRIPE / math.sqrt(2)  # perpendicular distance between stripes
    light = "#{:02x}{:02x}{:02x}".format(*(round(v + (255 - v) * 0.45) for v in rgb))
    t = num(period, 3)
    return (
        f'<pattern id="tape-{col[1:]}" patternUnits="userSpaceOnUse" width="{t}" height="{t}" '
        f'patternTransform="rotate(-45)">'
        f'<rect width="{t}" height="{t}" fill="{light}"/>'
        f'<rect width="{num(period / 2, 3)}" height="{t}" fill="{col}"/></pattern>'
    )


def tape_markup(t: Tape, o, defs: list[str], seen: set[str], size: tuple[float, float]) -> str | None:
    rgb = tuple(round(c * 255) for c in t.color[:3])
    col = hexcol(t.color)
    if t.polygon:
        pts = " ".join(f"{num(x, o.precision)},{num(y, o.precision)}" for x, y in t.polygon)
        if t.revealed:
            return el("polygon", points=pts, fill="none", stroke=col, stroke_width=num(EDGE, 3))
        if col not in seen:
            seen.add(col)
            defs.append(tape_pattern(col, rgb))
        return el("polygon", points=pts, fill=f"url(#tape-{col[1:]})")
    s = t.stroke
    w = 2 * s.width  # the renderer draws freehand tape 2 x width thick, whatever the pressure flag
    eps = 0.5 * 10**-o.precision
    runs = [r for r in (dedupe(r, eps) for r in s.runs()) if r]
    pieces = [(w, rdp(r, o.simplify)) for r in runs]
    if not pieces:
        return None
    common = dict(class_="tape")
    if t.revealed:  # outline only: the band minus its inside, as a mask
        mid = f"tm{len(defs)}"
        white = "".join(el(n_, **a) for n_, a in draw(pieces, "#fff", o))
        inner = [(pw - 2 * EDGE, pts) for pw, pts in pieces if pw - 2 * EDGE > 0]
        black = "".join(el(n_, **a) for n_, a in draw(inner, "#000", o))
        W, H = size
        defs.append(
            # <defs> content does not inherit the <g> that sets LOOK, and an unfilled-by-default
            # path would be painted black, so the mask carries the stroke look itself
            f'<mask id="{mid}" maskUnits="userSpaceOnUse" x="0" y="0" '
            f'width="{num(W, 2)}" height="{num(H, 2)}" {LOOK}>'
            f"{white}{black}</mask>"
        )
        common["mask"] = f"url(#{mid})"
        return emit(draw(pieces, col, o), common)
    if col not in seen:
        seen.add(col)
        defs.append(tape_pattern(col, rgb))
    return emit(draw(pieces, f"url(#tape-{col[1:]})", o), common)


# --------------------------------------------------------------------------------- page
class _BaseOnly(Notebook):
    """The notebook without ink: page background and image elements only (for --background embed)."""

    def page_strokes(self, page):
        return []

    def page_shapes(self, page):
        return []

    def page_tapes(self, page):
        return []


def page_svg(nb: Notebook, base: Notebook | None, page: Page, o) -> tuple[str, dict]:
    W, H = page.size
    items = [(s, "ink") for s in nb.page_strokes(page)] + [(s, "shape") for s in nb.page_shapes(page)]
    entries: list[tuple[tuple[float, int], str, str]] = []  # (written at, stream position), kind, markup
    created = [int.from_bytes(s.clocks[0], "big") for s, _ in items if s.clocks and not s.tape]
    t0 = min(created, default=0)
    for i, (s, src) in enumerate(items, 1):
        if s.tape:
            continue
        kind = {ink.STYLE_HIGHLIGHTER: "hl", ink.STYLE_PEN: "pen"}.get(s.style)
        runs = [r for r in s.runs() if r]
        if kind is None or not runs:
            continue
        pieces = pieces_for(s, runs, o)
        if not pieces:
            continue
        common = dict(id=f"s{i:04d}", class_=kind if src == "ink" else f"{kind} shape")
        if s.clocks:  # seconds since the page's first stroke, so a script can replay in writing order
            common["data_t"] = num((int.from_bytes(s.clocks[0], "big") - t0) / 1e6, 3)
        if kind == "pen" and s.color[3] < 0.999:  # the renderer honours pen alpha, not highlighter alpha
            common["opacity"] = num(s.color[3], 3)
        written = int.from_bytes(s.clocks[0], "big") if s.clocks else math.inf
        entries.append(((written, i), kind, emit(draw(pieces, hexcol(s.color), o), common)))

    defs: list[str] = []
    seen: set[str] = set()
    tapes = (
        [] if o.no_tape else [m for t in nb.page_tapes(page) if (m := tape_markup(t, o, defs, seen, (W, H)))]
    )

    body: list[str] = []
    if o.background not in ("none", "embed"):  # a solid colour, normalised to #rrggbb in main()
        body.append(el("rect", width=num(W, 2), height=num(H, 2), fill=o.background))
    elif o.background == "embed":
        buf = io.BytesIO()
        base.render_page(page.index, o.raster_scale).save(buf, "PNG", optimize=True)
        uri = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
        body.append(
            el(
                "image",
                x=0,
                y=0,
                width=num(W, 2),
                height=num(H, 2),
                preserveAspectRatio="none",
                xlink_href=uri,
            )
        )
    if o.order == "time":
        # one layer in the order the strokes were written; highlighter strokes blend with multiply, each
        # run of consecutive ones sharing one opacity so that their overlaps do not darken
        parts: list[str] = []
        run: list[str] = []

        def flush() -> None:
            if run:
                parts.append(
                    f'<g class="hl-run" opacity="{HIGHLIGHT_ALPHA}" style="mix-blend-mode:multiply">'
                    + "".join(run)
                    + "</g>"
                )
                run.clear()

        for _, kind, markup in sorted(entries, key=lambda e: e[0]):
            if kind == "hl":
                run.append(markup)
            else:
                flush()
                parts.append(markup)
        flush()
        body.append(f'<g id="ink" {LOOK}>' + "".join(parts) + "</g>")
    else:
        hl = [m for _, kind, m in entries if kind == "hl"]
        pens = [m for _, kind, m in entries if kind != "hl"]
        if hl:
            body.append(f'<g id="highlighter" opacity="{HIGHLIGHT_ALPHA}" {LOOK}>' + "".join(hl) + "</g>")
        body.append(f'<g id="ink" {LOOK}>' + "".join(pens) + "</g>")
    if tapes:
        body.append(f'<g id="tape" {LOOK}>' + "".join(tapes) + "</g>")

    svg = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
        f'viewBox="0 0 {num(W, 2)} {num(H, 2)}" '
        f'width="{num(W * o.scale, 2)}" height="{num(H * o.scale, 2)}">\n'
        f"<title>{escape(nb.title or nb.path.stem)} - page {page.index + 1}</title>\n"
        + (f"<defs>{''.join(defs)}</defs>\n" if defs else "")
        + "\n".join(body)
        + "\n</svg>\n"
    )
    info = {
        "strokes": len(entries),
        "tapes": len(tapes),
        "images": sum(len(nb.layer_images(l)) for l in page.layer_ids),
    }
    return svg, info


# ----------------------------------------------------------------------------------- cli
def main() -> None:
    ap = argparse.ArgumentParser(
        description="Export a .noteful notebook as SVG, one file per page, centreline strokes."
    )
    ap.add_argument("notebook", type=Path)
    ap.add_argument(
        "-o",
        "--output",
        type=Path,
        help="output directory (default NAME-svg/), or a .svg file for a single page",
    )
    ap.add_argument(
        "--prefix",
        metavar="PREFIX",
        help="name pages PREFIX-p1.svg, PREFIX-p2.svg, ...; a directory in the prefix is where they go "
        "(default NAME-p1.svg, ... in NAME-svg/)",
    )
    ap.add_argument(
        "--order",
        choices=["layers", "time"],
        default="time",
        help="layers: highlighter strokes in a layer under the ink; time  (default): one layer in the order "
        "the strokes were written, highlighters blending with multiply (ids stay stream positions)",
    )
    ap.add_argument(
        "--page", default="all", help="page number (1-based), a range like 2-4, or 'all' (default)"
    )
    ap.add_argument(
        "--scale", type=float, default=1.0, help="width/height attributes = page units x scale (default 1)"
    )
    ap.add_argument("--background", default="none", metavar="none|embed|COLOR",
                    help="none: transparent; a colour name or #rrggbb (black, white, ...): solid rectangle; "
                    "embed: paper/PDF + images as an embedded PNG")  # fmt: skip
    ap.add_argument(
        "--raster-scale",
        type=float,
        default=1.0,
        help="pixels per page unit of the embedded background (default 1)",
    )
    ap.add_argument(
        "--pressure",
        choices=["variable", "uniform"],
        default="variable",
        help="variable: split strokes where pressure changes the width; uniform: one mean width per stroke",
    )
    ap.add_argument(
        "--width-step",
        type=float,
        default=0.25,
        help="width change that starts a new piece, page units (default 0.25)",
    )
    ap.add_argument(
        "--simplify",
        type=float,
        default=0.0,
        help="Douglas-Peucker tolerance in page units (default 0 = off)",
    )
    ap.add_argument(
        "--smooth",
        action="store_true",
        help="join points with Catmull-Rom Bezier curves instead of straight lines",
    )
    ap.add_argument("--precision", type=int, default=2, help="decimals in coordinates (default 2)")
    ap.add_argument(
        "--no-tape", action="store_true", help="leave tape out (it is a pattern / mask, not a centreline)"
    )
    o = ap.parse_args()
    if o.background not in ("none", "embed"):
        try:
            o.background = "#{:02x}{:02x}{:02x}".format(*ImageColor.getrgb(o.background)[:3])
        except ValueError:
            raise SystemExit(
                f"--background: {o.background!r} is not none, embed, a colour name or #rrggbb"
            ) from None

    nb = Notebook(o.notebook)
    n = len(nb.pages)
    if o.page == "all":
        pages = list(range(n))
    elif "-" in o.page:
        lo, hi = (int(v) for v in o.page.split("-", 1))
        pages = list(range(lo - 1, min(hi, n)))
    else:
        pages = [int(o.page) - 1]
    if not pages or any(not 0 <= i < n for i in pages):
        raise SystemExit(f"page out of range: the notebook has {n} page(s)")

    single = o.output is not None and o.output.suffix.lower() == ".svg"
    if single and len(pages) != 1:
        raise SystemExit("-o FILE.svg needs exactly one page; give a directory for several")
    if single and o.prefix:
        raise SystemExit("--prefix names several files; it does not go with -o FILE.svg")
    prefix = Path(o.prefix) if o.prefix else None
    stem = prefix.name if prefix else o.notebook.stem
    outdir = None
    if not single:
        outdir = o.output or (prefix.parent if prefix else Path(f"{o.notebook.stem}-svg"))
    if outdir:
        outdir.mkdir(parents=True, exist_ok=True)
    base = _BaseOnly(o.notebook) if o.background == "embed" else None

    digits = len(str(n))
    for i in pages:
        svg, info = page_svg(nb, base, nb.pages[i], o)
        path = o.output if single else outdir / f"{stem}-p{i + 1:0{digits}d}.svg"
        path.write_text(svg, encoding="utf-8")
        kib = len(svg) / 1024
        print(f"page {i + 1}: {info['strokes']} strokes, {info['tapes']} tape(s), {kib:.0f} KiB -> {path}")
        if info["images"] and o.background != "embed":
            print(f"  note: page {i + 1} has {info['images']} image element(s) that are not in the SVG "
                  f"(use --background embed)", file=sys.stderr)  # fmt: skip


if __name__ == "__main__":
    main()
