# Tactiverge Academy — companion code for "Inverse kinematics and the workspace"
# Lesson: https://tactiverge.win/academy/robotics-foundations/mathematical-foundations-of-movement/inverse-kinematics-and-workspace/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import math

def solve_ik(L1, L2, x, y):
    """Return a list of (theta1, theta2) solutions in degrees (may be empty)."""
    c2 = (x * x + y * y - L1 * L1 - L2 * L2) / (2 * L1 * L2)
    if c2 > 1 or c2 < -1:
        return []                                  # out of reach
    solutions = []
    for sign in (+1, -1):                          # elbow down, elbow up
        t2 = sign * math.acos(c2)
        t1 = math.atan2(y, x) - math.atan2(L2 * math.sin(t2), L1 + L2 * math.cos(t2))
        solutions.append((math.degrees(t1), math.degrees(t2)))
    return solutions

def closest(solutions, current):
    """Pick the solution needing the least total joint movement."""
    return min(solutions, key=lambda s: abs(s[0] - current[0]) + abs(s[1] - current[1]))

L1, L2 = 20, 15
for target in [(22, 18), (34, 0), (34.9, 0), (40, 10), (3, 2)]:
    sols = solve_ik(L1, L2, *target)
    shown = ", ".join(f"({a:6.2f}, {b:6.2f})" for a, b in sols) or "unreachable"
    print(f"target {target}: {shown}")

a, b = closest(solve_ik(L1, L2, 22, 18), current=(60, -60))
print(f"closest to (60, -60): ({a:.2f}, {b:.2f})")
