"""CoreXY geometry shared by the XY stage wrapper and the software planner.

Pure functions, no hardware and no `ufp` import, so planning code can use them
without the library installed.

The motors move along displacements a and b from their limit switches:

    x = (a + b) / 2          a = x + y
    y = (a - b) / 2          b = x - y

(x, y) = (0, 0) is where both motors sit on their switches (the homed position).
The usable region is an axis-aligned box x_min <= x <= x_max, y_min <= y <= y_max
that contains (0, 0). Each motor's range follows from it (`motor_ranges`): a motor may
travel past its switch, as long as the tool stays inside the box.
"""
import math

EPS = 1e-9   # mm, tolerance of the workspace test


def xy_to_ab(x, y):
    return x + y, x - y


def ab_to_xy(a, b):
    return (a + b) / 2, (a - b) / 2


def check_limits(x_min, x_max, y_min, y_max):
    """ValueError unless the box is non-empty and contains the homed position (0, 0)."""
    if not (x_min < x_max and y_min < y_max):
        raise ValueError(f"x and y limits must have min < max, got x {x_min}..{x_max}, y {y_min}..{y_max}")
    if not (x_min <= 0 <= x_max and y_min <= 0 <= y_max):
        raise ValueError(f"the limits x {x_min:g}..{x_max:g}, y {y_min:g}..{y_max:g} must contain the "
                         "homed position (0, 0): the stage sits there after homing")


def workspace_corners(x_min, x_max, y_min, y_max):
    """Corners of the usable box as (x, y) in mm, in order around it."""
    return [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]


def in_workspace(x, y, x_min, x_max, y_min, y_max, tol=EPS):
    return x_min - tol <= x <= x_max + tol and y_min - tol <= y <= y_max + tol


def motor_ranges(x_min, x_max, y_min, y_max):
    """((a_min, a_max), (b_min, b_max)): the displacement each motor needs to cover the box,
    measured from its limit switch. Negative means past the switch."""
    return (x_min + y_min, x_max + y_max), (x_min - y_max, x_max - y_min)


def peak_share(dx, dy):
    """Largest share of a straight move that one motor has to travel: motor mm per mm
    along the line, between 1 (pure x or y) and sqrt(2) (45 degrees)."""
    length = math.hypot(dx, dy)
    return max(abs(dx + dy), abs(dx - dy)) / length if length > EPS else 1.0


def apply_motor_limits(v, a, peak, motor_v_max=None, motor_a_max=None):
    """Slow a line move (speed v mm/s, acceleration a mm/s^2 along the line) so that no motor
    exceeds its own limit. `peak` is `peak_share(dx, dy)`. Direction is kept."""
    if motor_v_max is not None and v * peak > motor_v_max:
        v = motor_v_max / peak
    if motor_a_max is not None and a * peak > motor_a_max:
        a = motor_a_max / peak
    return v, a
