"""SVG -> list of Polyline (mm, +Y up). Uses `svgelements` for parsing and transforms since that is hard to parse correctly."""
import numpy as np
from svgelements import SVG, Close, Line, Move, Path, Shape

from geometry import Polyline

PX_TO_MM = 25.4 / 96.0   # math: 96 px per inch, convert to mm


def load_svg(source) -> list[Polyline]:
    """Read every visible shape. Handles each shape individually.

    text elements are ignored: convert text to paths in the drawing tool if needed.
    """
    svg = SVG.parse(source) # svgelements parse the SVG file for us, very helpful
    out = []
    for el in svg.elements():
        if not isinstance(el, Shape) or el.values.get("visibility") == "hidden":
            continue
        color = _color_of(el)
        for sub in Path(el).as_subpaths():
            pl = _subpath_to_polyline(Path(sub))
            if pl is not None:
                pl.points = pl.points * [PX_TO_MM, -PX_TO_MM]   # px -> mm, flip Y (SVG Y points down)
                pl.color = color
                out.append(pl) # add the polyline to the output list
    if not out:
        raise ValueError("SVG contains no drawable shapes (is the text converted to paths?)")
    return out # return the list of polylines


def _color_of(el):
    for c in (el.stroke, el.fill):
        if c is not None and c.value is not None and c.alpha > 0:
            return c.hex[:7] # return the hex color code without the alpha channel
    return None


def _subpath_to_polyline(sub: Path, step_px=2.0, min_pts=16):
    pts, closed = [], False
    for seg in sub: # iterate through the segments of the subpath
        if isinstance(seg, Move):
            pts.append((seg.end.x, seg.end.y))
        elif isinstance(seg, Close):
            closed = True
        elif isinstance(seg, Line):
            pts.append((seg.end.x, seg.end.y))
        else:  # curves and arcs: oversample uniformly in t
            n = max(min_pts, int(np.ceil(seg.length(error=1e-4) / step_px)) + 1) # add error=1e-4 to avoid rounding errors
            pts.extend(map(tuple, seg.npoint(np.linspace(0, 1, n))[1:]))
    pts = np.asarray(pts, dtype=float)
    if len(pts) < 2:
        return None
    if np.allclose(pts[0], pts[-1]):
        closed, pts = True, pts[:-1]   # store closed loops without the repeated end point
    if len(pts) < 2:
        return None
    return Polyline(pts, closed)
