#!/usr/bin/env python3
"""
cubic2quadratic.py - replace every cubic Bezier segment of an SVG path by ONE
quadratic Bezier (Q) or ONE circular arc (A). The result is a new, different
curve (not an error-controlled approximation); the endpoints are kept.

  --curve quad  (default)
      Control point = intersection of the start tangent line (P0->P1) and the
      end tangent line (P3->P2). Both end tangents are preserved exactly.
      If there is no usable intersection (parallel tangents, S-shape, the
      intersection lies behind an endpoint or absurdly far away), --fallback:
        best   control point (3*P1 - P0 + 3*P2 - P3)/4  (least-error single
               quadratic; default)
        p1     control point P1 (keeps the start tangent only)
        p2     control point P2 (keeps the end tangent only)
        split  cut the cubic at t=0.5 and convert each half (up to 4 levels)
      Closed-loop cubics (P0 = P3) are always cut at t=0.5.

  --curve arc
      Circular arc through P0 and P3. The chord-to-tangent angle is the mean of
      the start and end angles, so both tangents are matched exactly when they
      make equal angles with the chord (isosceles control triangle), and
      approximately otherwise. S-shaped cubics (the two angles have opposite
      signs) are cut at t=0.5 and converted piecewise; (nearly) straight
      cubics become L.

Input: path data with M L H V C S Z (absolute or relative).
Usage:
  python cubic2quadratic.py --d "M0 0 C0 5 5 10 10 10"
  python cubic2quadratic.py in.svg -c arc -o out.svg
  python cubic2quadratic.py in.svg --fallback split
Requires: numpy

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

"""

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

import numpy as np

# ---------------------------------------------------------- user settings
# These apply when the script is run WITHOUT command-line arguments.
INPUT = "in.svg"
OUTPUT = "out.svg"
CURVE = "arc"  # "quad" | "arc"
FALLBACK = "best"  # quad only: "best" | "p1" | "p2" | "split"
MAX_RATIO = 4.0  # quad: tangent intersection farther than MAX_RATIO*chord -> fallback
MAX_DEPTH = 4  # maximum number of recursive halvings
ARC_TOL = 0.01 # arc: split if the cubic midpoint is farther than ARC_TOL*chord from the arc
PRECISION = None  # decimals in output; None = chosen from the path's extent

NUM = r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?"
TOKEN = re.compile(r"([A-Za-z])|(" + NUM + ")")
ARGC = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "S": 4}
STATS = {"fallback": 0}  # cubics (top level) that needed the fallback / a split


# --------------------------------------------------------------- parsing
def parse_path(d):
    """Parse path data into ops: ('M',p) ('L',p) ('C',p1,p2,p3) ('Z',)."""
    leftover = re.sub(NUM, "", d)
    bad = set(re.findall(r"[A-Za-z]", leftover)) - set("MmLlHhVvCcSsZz")
    if bad:
        raise ValueError(
            "Unsupported path commands %s: only M L H V C S Z (abs/rel) "
            "are accepted." % sorted(bad)
        )
    items = [m.group(1) or float(m.group(2)) for m in TOKEN.finditer(d)]
    ops = []
    pos = np.zeros(2)
    start = pos.copy()
    last_c2 = None  # 2nd control point of the previous C/S (for S reflection)
    cmd, i = None, 0
    while i < len(items):
        if isinstance(items[i], str):
            cmd = items[i]
            i += 1
            if cmd in "Zz":
                ops.append(("Z",))
                pos = start.copy()
                last_c2 = None
                continue
        elif cmd is None:
            raise ValueError("Path data must start with a command")
        if cmd in "Zz":
            raise ValueError("Unexpected number after Z")
        c, rel = cmd.upper(), cmd.islower()
        n = ARGC[c]
        args = items[i : i + n]
        if len(args) < n or any(isinstance(a, str) for a in args):
            raise ValueError("Bad arguments for command %s" % cmd)
        i += n
        off = pos if rel else np.zeros(2)
        if c in "ML":
            p = np.array(args) + off
            ops.append((c, p))
            pos, last_c2 = p, None
            if c == "M":
                start = p.copy()
                cmd = "l" if rel else "L"  # implicit lineto after moveto
        elif c == "H":
            p = np.array([args[0] + (pos[0] if rel else 0), pos[1]])
            ops.append(("L", p))
            pos, last_c2 = p, None
        elif c == "V":
            p = np.array([pos[0], args[0] + (pos[1] if rel else 0)])
            ops.append(("L", p))
            pos, last_c2 = p, None
        elif c == "C":
            p1, p2, p3 = (np.array(args[k : k + 2]) + off for k in (0, 2, 4))
            ops.append(("C", p1, p2, p3))
            pos, last_c2 = p3, p2
        else:  # S: first control point is the reflection of the previous one
            p1 = 2 * pos - last_c2 if last_c2 is not None else pos.copy()
            p2, p3 = (np.array(args[k : k + 2]) + off for k in (0, 2))
            ops.append(("C", p1, p2, p3))
            pos, last_c2 = p3, p2
    return ops


# ------------------------------------------------------------- geometry
def cross(a, b):
    return a[0] * b[1] - a[1] * b[0]


def unit(v):
    n = math.hypot(v[0], v[1])
    return v / n if n > 1e-12 else None


def first(*vs):
    for v in vs:
        if v is not None:
            return v
    return None


def split_cubic(P0, P1, P2, P3):
    """de Casteljau split at t = 0.5."""
    a, b, c = (P0 + P1) / 2, (P1 + P2) / 2, (P2 + P3) / 2
    d, e = (a + b) / 2, (b + c) / 2
    m = (d + e) / 2
    return (P0, a, d, m), (m, e, c, P3)


def prepare(P0, P1, P2, P3):
    """Common checks. Returns ('L', ...) result or (None, tA, tB, chord, L)."""
    tA = first(unit(P1 - P0), unit(P2 - P0), unit(P3 - P0))
    tB = first(unit(P3 - P2), unit(P3 - P1), unit(P3 - P0))
    c = P3 - P0
    L = math.hypot(c[0], c[1])
    poly = sum(math.hypot(*(q - p)) for p, q in ((P0, P1), (P1, P2), (P2, P3)))
    if tA is None or tB is None or poly < 1e-12:
        return [("L", P3)], None
    if L < 1e-6 * poly:  # closed loop: no chord, must be cut
        return None, "loop"
    e = c / L
    if abs(cross(e, P1 - P0)) < 1e-9 * L and abs(cross(e, P2 - P0)) < 1e-9 * L:
        return [("L", P3)], None  # control points on the chord: straight
    return None, (tA, tB, c, L, e)


# ------------------------------------------------------- quadratic (Q)
def to_quad(P0, P1, P2, P3, fallback, max_ratio, depth=0):
    res, info = prepare(P0, P1, P2, P3)
    if res is not None:
        return res
    if info == "loop":
        if depth == 0:
            STATS["fallback"] += 1
        if depth < MAX_DEPTH:
            h1, h2 = split_cubic(P0, P1, P2, P3)
            return to_quad(*h1, fallback, max_ratio, depth + 1) + to_quad(
                *h2, fallback, max_ratio, depth + 1
            )
        return [("L", P3)]
    tA, tB, c, L, _ = info
    ctrl = None
    det = cross(tA, tB)
    if abs(det) > 1e-9:
        # P0 + a*tA = P3 - b*tB   ->   a*tA + b*tB = c
        a = cross(c, tB) / det
        b = cross(tA, c) / det
        if a > 0 and b > 0 and max(a, b) <= max_ratio * L:
            ctrl = P0 + a * tA
    if ctrl is None:  # no usable tangent intersection
        if depth == 0:
            STATS["fallback"] += 1
        if fallback == "split" and depth < MAX_DEPTH:
            h1, h2 = split_cubic(P0, P1, P2, P3)
            return to_quad(*h1, fallback, max_ratio, depth + 1) + to_quad(
                *h2, fallback, max_ratio, depth + 1
            )
        ctrl = {"p1": P1, "p2": P2}.get(fallback, (3 * P1 - P0 + 3 * P2 - P3) / 4)
    return [("Q", ctrl, P3)]


# ------------------------------------------------------------- arc (A)
def to_arc(P0, P1, P2, P3, depth=0):
    res, info = prepare(P0, P1, P2, P3)
    if res is not None:
        return res
    if info == "loop":
        if depth < MAX_DEPTH:
            if depth == 0:
                STATS["fallback"] += 1
            h1, h2 = split_cubic(P0, P1, P2, P3)
            return to_arc(*h1, depth + 1) + to_arc(*h2, depth + 1)
        return [("L", P3)]
    tA, tB, c, L, e = info
    al = math.atan2(cross(tA, e), float(tA @ e))  # tangent A -> chord
    be = math.atan2(cross(e, tB), float(e @ tB))  # chord -> tangent B
    if al * be < 0 and abs(al) + abs(be) > 2 * math.pi - 1e-3:
        # both angles are close to +-pi: same direction, opposite sign by wrap
        if al < 0:
            al += 2 * math.pi
        else:
            be += 2 * math.pi
    if al * be < 0 and max(abs(al), abs(be)) > 1e-3 and depth < MAX_DEPTH:
        if depth == 0:
            STATS["fallback"] += 1
        h1, h2 = split_cubic(P0, P1, P2, P3)  # S-shape: needs two arcs
        return to_arc(*h1, depth + 1) + to_arc(*h2, depth + 1)
    th = 0.5 * (al + be)  # chord-tangent angle; central angle is 2*th
    if th > math.pi:
        th -= 2 * math.pi
    elif th < -math.pi:
        th += 2 * math.pi
    if abs(math.sin(th)) < 1e-6:
        if abs(th) > math.pi / 2 and depth < MAX_DEPTH:  # (nearly) full circle
            if depth == 0:
                STATS["fallback"] += 1
            h1, h2 = split_cubic(P0, P1, P2, P3)
            return to_arc(*h1, depth + 1) + to_arc(*h2, depth + 1)
        return [("L", P3)]
    R = L / (2 * abs(math.sin(th)))
    # Mittenabgleich: weicht die Kubik bei t=0.5 zu stark vom Arc ab -> teilen
    sag = R * (1 - math.cos(th))  # Pfeilhoehe des Arcs
    nrm = np.array([-e[1], e[0]])
    mid = (P0 + P3) / 2
    Bm = (P0 + 3 * P1 + 3 * P2 + P3) / 8  # Kubik bei t=0.5
    err = min(np.linalg.norm(Bm - (mid + nrm * sag)),
              np.linalg.norm(Bm - (mid - nrm * sag)))
    if err > ARC_TOL * L and depth < MAX_DEPTH:
        if depth == 0:
            STATS["fallback"] += 1
        h1, h2 = split_cubic(P0, P1, P2, P3)
        return to_arc(*h1, depth + 1) + to_arc(*h2, depth + 1)
    large = 1 if abs(th) > math.pi / 2 else 0
    sweep = 1 if th > 0 else 0  # SVG sweep=1: positive angle direction
    return [("A", R, large, sweep, P3)]

# ---------------------------------------------------------------- driver
def convert_ops(ops, curve, fallback, max_ratio):
    out, pos, start = [], None, None
    for op in ops:
        k = op[0]
        if k == "M":
            out.append(op)
            pos = start = op[1]
        elif k == "Z":
            out.append(op)
            pos = start
        elif pos is None:
            raise ValueError("Path must start with M")
        elif k == "L":
            out.append(op)
            pos = op[1]
        else:  # C
            if curve == "arc":
                out += to_arc(pos, op[1], op[2], op[3])
            else:
                out += to_quad(pos, op[1], op[2], op[3], fallback, max_ratio)
            pos = op[3]
    return out


def auto_precision(ops):
    pts = [p for op in ops for p in op[1:]]
    if not pts:
        return 3
    a = np.array(pts)
    extent = float(np.max(a.max(axis=0) - a.min(axis=0)))
    if extent <= 0:
        return 3
    return max(3, 4 - int(math.floor(math.log10(extent))))


def fmt(x, p):
    s = "%.*f" % (p, x)
    if "." in s:
        s = s.rstrip("0").rstrip(".")
    return "0" if s in ("", "-0") else s


def to_d(ops, precision):
    f = lambda v: fmt(v, precision)
    parts = []
    for op in ops:
        k = op[0]
        if k in "ML":
            parts.append("%s%s %s" % (k, f(op[1][0]), f(op[1][1])))
        elif k == "Q":
            parts.append(
                "Q%s %s %s %s" % (f(op[1][0]), f(op[1][1]), f(op[2][0]), f(op[2][1]))
            )
        elif k == "A":
            r = f(op[1])
            parts.append(
                "A%s %s 0 %d %d %s %s" % (r, r, op[2], op[3], f(op[4][0]), f(op[4][1]))
            )
        else:
            parts.append("Z")
    return " ".join(parts)


def convert_path(d, curve="quad", fallback="best", max_ratio=MAX_RATIO,
                 precision=None, verbose=True):
    ops = parse_path(d)
    STATS["fallback"] = 0
    out = convert_ops(ops, curve, fallback, max_ratio)
    if precision is None:
        precision = auto_precision(ops)
    if verbose:
        nc = sum(1 for o in ops if o[0] == "C")
        no = sum(1 for o in out if o[0] in "QA")
        nl = sum(1 for o in out if o[0] == "L") - sum(1 for o in ops if o[0] == "L")
        what = "split (S-shape/loop)" if curve == "arc" else "fallback '%s'" % fallback
        print(
            "%d cubic -> %d %s%s; %d x %s"
            % (nc, no, "arc" if curve == "arc" else "quadratic",
               "" if nl <= 0 else " + %d line(s) (straight/degenerate)" % nl,
               STATS["fallback"], what),
            file=sys.stderr,
        )
    return to_d(out, precision)


def convert_svg(src, dst, **kw):
    for pfx, uri in [
        ("", "http://www.w3.org/2000/svg"),
        ("xlink", "http://www.w3.org/1999/xlink"),
        ("inkscape", "http://www.inkscape.org/namespaces/inkscape"),
        ("sodipodi", "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"),
    ]:
        ET.register_namespace(pfx, uri)
    parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
    tree = ET.parse(src, parser=parser)
    count = 0
    for el in tree.iter():
        tag = el.tag.rsplit("}", 1)[-1] if isinstance(el.tag, str) else ""
        if tag == "path" and "d" in el.attrib:
            try:
                el.set("d", convert_path(el.get("d"), **kw))
            except ValueError as err:
                ident = el.get("id")
                print(
                    "warning: path%s left unchanged: %s"
                    % (" '%s'" % ident if ident else "", err),
                    file=sys.stderr,
                )
                continue
            count += 1
    tree.write(dst, encoding="utf-8", xml_declaration=True)
    return count


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument("input", nargs="?", help="input SVG file")
    ap.add_argument("--d", help="path data string instead of a file")
    ap.add_argument("-c", "--curve", choices=("quad", "arc"), default=CURVE)
    ap.add_argument(
        "--fallback",
        choices=("best", "p1", "p2", "split"),
        default=FALLBACK,
        help="quad only: control point when the tangents give no intersection",
    )
    ap.add_argument("--max-ratio", type=float, default=MAX_RATIO)
    ap.add_argument(
        "-o", "--output",
        help="output SVG (default: <input>_quad.svg or <input>_arc.svg)",
    )
    ap.add_argument(
        "--precision", type=int, default=PRECISION,
        help="decimals in output (default: chosen from the path's extent)",
    )
    a = ap.parse_args()
    kw = dict(curve=a.curve, fallback=a.fallback, max_ratio=a.max_ratio,
              precision=a.precision)
    if a.d:
        print(convert_path(a.d, **kw))
    elif a.input:
        suffix = "_arc.svg" if a.curve == "arc" else "_quad.svg"
        base, ext = os.path.splitext(a.input)
        if ext.lower() != ".svg":
            base = a.input
        dst = a.output or base + suffix
        k = convert_svg(a.input, dst, **kw)
        print("converted %d path(s) -> %s" % (k, dst), file=sys.stderr)
    else:
        ap.error("give an input SVG or --d")


if __name__ == "__main__":
    if len(sys.argv) > 1:
        main()
    else:
        convert_svg(INPUT, OUTPUT, curve=CURVE, fallback=FALLBACK,
                    max_ratio=MAX_RATIO, precision=PRECISION)