#!/usr/bin/env python3
"""
Convert SVG path data between absolute and relative coordinates.

No arguments: input.svg -> output.svg (script directory), settings below.
With arguments:
    python svgpath_convert.py rel|abs [in.svg] [-o out.svg] [-p 3]
    python svgpath_convert.py rel|abs --path "m 10 10 l 5 5 z"

https://www.sqrt.ch/Buch/svgpath_convert.py (with claude.ai)

"""
import argparse
import os
import re
import sys

# --- Defaults (used when run without arguments) ---
HERE = os.path.dirname(os.path.abspath(__file__))
INPUT, OUTPUT = os.path.join(HERE, "input.svg"), os.path.join(HERE, "output.svg")
MODE = "rel"  # "rel" or "abs"
PREC = 10     # decimal places

ARGS = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "T": 2, "A": 7, "Z": 0}
NUM = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
SEP = re.compile(r"[\s,]*")


def parse(d):
    """d -> [(cmd, [args])]; resolves implicit repeats and packed arc flags ("00.5.5")."""
    pos, out = 0, []
    while (pos := SEP.match(d, pos).end()) < len(d):
        cmd = d[pos]
        if cmd.upper() not in ARGS:
            raise ValueError(f"Unexpected character {cmd!r} at position {pos}")
        pos += 1
        n, first = ARGS[cmd.upper()], True
        if n == 0:
            out.append((cmd, []))
            continue
        while True:
            pos = SEP.match(d, pos).end()
            if not NUM.match(d, pos):
                if first:
                    raise ValueError(f"Number expected after {cmd!r} at position {pos}")
                break
            args = []
            for i in range(n):
                pos = SEP.match(d, pos).end()
                if cmd in "aA" and i in (3, 4):  # flags: exactly one character
                    m = re.compile("[01]").match(d, pos)
                else:
                    m = NUM.match(d, pos)
                if not m:
                    raise ValueError(f"Number/flag expected at position {pos}")
                args.append(float(m.group()))
                pos = m.end()
            out.append((cmd, args))
            cmd = {"M": "L", "m": "l"}.get(cmd, cmd)  # extra pairs after M are L
            first = False
    return out


def to_abs_segments(raw):
    """Normalize everything to absolute coordinates: [(CMD, [args])]."""
    cx = cy = sx = sy = 0.0
    out = []
    for cmd, a in raw:
        rel, C, a = cmd.islower(), cmd.upper(), list(a)
        if C == "Z":
            cx, cy = sx, sy
        elif C == "H":
            a[0] += cx * rel
            cx = a[0]
        elif C == "V":
            a[0] += cy * rel
            cy = a[0]
        else:
            first = 5 if C == "A" else 0  # arcs: only the endpoint
            for i in range(first, len(a)):
                a[i] += (cy if (i - first) % 2 else cx) * rel
            cx, cy = a[-2], a[-1]
            if C == "M":
                sx, sy = cx, cy
        out.append((C, a))
    return out


def fmt(v, prec):
    s = f"{round(v, prec):.{prec}f}"
    s = s.rstrip("0").rstrip(".") if "." in s else s
    return "0" if s in ("-0", "") else s


def emit(segs, prec):
    """[(cmd, [floats])] -> d string; repeated command letters are omitted."""
    out, prev = [], None
    for cmd, args in segs:
        body = ""
        for i, v in enumerate(args):
            t = str(int(v)) if cmd in "aA" and i in (3, 4) else fmt(v, prec)
            body += (" " + t) if (body and not t.startswith("-")) else t
        same = cmd == prev and cmd not in "mMzZ"
        out.append((" " * (not body.startswith("-")) if same else cmd) + body)
        prev = cmd
    return "".join(out)


def to_absolute(d, prec=PREC):
    return emit(to_abs_segments(parse(d)), prec)


def to_relative(d, prec=PREC):
    """Absolute -> relative. The cursor follows the *rounded* deltas so that
    rounding errors do not accumulate."""
    ex = ey = sx = sy = 0.0
    out = []
    for C, a in to_abs_segments(parse(d)):
        r = list(a)
        if C == "Z":
            ex, ey = sx, sy
        elif C in "HV":
            r[0] = round(a[0] - (ex if C == "H" else ey), prec)
            ex, ey = (ex + r[0], ey) if C == "H" else (ex, ey + r[0])
        else:
            first = 5 if C == "A" else 0  # arcs: only the endpoint is relative
            for i in range(first, len(a), 2):
                r[i] = round(a[i] - ex, prec)
                r[i + 1] = round(a[i + 1] - ey, prec)
            ex, ey = ex + r[-2], ey + r[-1]
            if C == "M":
                sx, sy = ex, ey
        out.append((C.lower(), r))
    return emit(out, prec)


D_ATTR = re.compile(r"""(\sd\s*=\s*)(["'])(.*?)\2""", re.DOTALL)


def convert_svg(text, mode=MODE, prec=PREC):
    """Replace all d="..." attributes; the rest of the SVG stays untouched."""
    func = to_absolute if mode == "abs" else to_relative
    return D_ATTR.sub(lambda m: f"{m[1]}{m[2]}{func(m[3], prec)}{m[2]}", text)


def convert_file(inp=INPUT, out=OUTPUT, mode=MODE, prec=PREC):
    with open(inp, encoding="utf-8") as f:
        result = convert_svg(f.read(), mode, prec)
    with open(out, "w", encoding="utf-8") as f:
        f.write(result)
    print(f"{mode}: {inp} -> {out}")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("mode", choices=["abs", "rel"])
    ap.add_argument("input", nargs="?", default=INPUT)
    ap.add_argument("--path", help="single path string (printed to stdout)")
    ap.add_argument("-o", "--output", default=OUTPUT)
    ap.add_argument("-p", "--precision", type=int, default=PREC)
    a = ap.parse_args()
    if a.path is not None:
        print((to_absolute if a.mode == "abs" else to_relative)(a.path, a.precision))
    else:
        convert_file(a.input, a.output, a.mode, a.precision)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        main()  # command line
    else:
        convert_file()  # defaults
