"""Normalized printable geometry
 helper functions to transform (evil) polylines into something that can be printed and make sure it behaves
"""
from dataclasses import dataclass

import numpy as np
from shapely.geometry import LineString

from config import Rect


@dataclass
class Polyline:
    points: np.ndarray          # (N, 2) float, mm
    closed: bool = False
    color: str | None = None    # color from the source design (hex), used for nozzle assignment
    nozzle: int = 0

    def length(self) -> float: # math to calculate the length of the polyline
        pts = np.vstack([self.points, self.points[:1]]) if self.closed else self.points
        return float(np.linalg.norm(np.diff(pts, axis=0), axis=1).sum()) # evil one liner to calculate the length of the polyline

    def reversed(self) -> "Polyline": # math to reverse the polyline
        return Polyline(self.points[::-1].copy(), self.closed, self.color, self.nozzle)


def simplify(paths: list[Polyline], tolerance: float) -> list[Polyline]:
    """ (shapely): drop points while staying within tolerance mm of the original."""
    out = []
    for p in paths: # iterate through the polylines
        pts = np.vstack([p.points, p.points[:1]]) if p.closed else p.points
        s = np.asarray(LineString(pts).simplify(tolerance, preserve_topology=False).coords) # simplify the polyline using shapely
        if p.closed:
            s = s[:-1]
        if len(s) >= 2:
            out.append(Polyline(s, p.closed, p.color, p.nozzle))
    return out


def bounds(paths: list[Polyline]) -> Rect:
    allpts = np.vstack([p.points for p in paths]) # stack the points of the polylines into a single array
    (x0, y0), (x1, y1) = allpts.min(axis=0), allpts.max(axis=0)
    return Rect(float(x0), float(x1), float(y0), float(y1))


def place_in_area(paths: list[Polyline], area: Rect, margin=0.0, fit=True, max_size=None) -> list[Polyline]:
    """Center the design in area. If fit, scale (aspect preserved) to fill area minus margin.

    """
    b = bounds(paths)
    w, h = b.x_max - b.x_min, b.y_max - b.y_min # width and height of the bounding box
    avail_w, avail_h = (area.x_max - area.x_min) - 2 * margin, (area.y_max - area.y_min) - 2 * margin
    scale = 1.0 # initial scale is 1.0
    if fit:
        scale = min(avail_w / w if w > 0 else np.inf, avail_h / h if h > 0 else np.inf)
    if max_size is not None and max(w, h) * scale > max_size:
        scale = max_size / max(w, h)
    if w * scale > avail_w + 1e-6 or h * scale > avail_h + 1e-6: # if the design does not fit the print area, raise an error
        raise ValueError(f"Design ({w * scale:.1f} x {h * scale:.1f} mm) does not fit print area "
                         f"({avail_w:.1f} x {avail_h:.1f} mm after margin)")
    src_c = np.array([(b.x_min + b.x_max) / 2, (b.y_min + b.y_max) / 2])
    dst_c = np.array([(area.x_min + area.x_max) / 2, (area.y_min + area.y_max) / 2])
    return [Polyline((p.points - src_c) * scale + dst_c, p.closed, p.color, p.nozzle) for p in paths] # return the polylines in the print area
