"""Compute both planar arm poses and validate them with forward kinematics."""
import argparse
from math import acos, atan2, cos, degrees, hypot, sin


def inverse(x, y, l1, l2, branch):
    c2 = (x*x + y*y - l1*l1 - l2*l2) / (2*l1*l2)
    if abs(c2) > 1 + 1e-12:
        return None
    q2 = branch * acos(max(-1.0, min(1.0, c2)))
    q1 = atan2(y, x) - atan2(l2*sin(q2), l1 + l2*cos(q2))
    return q1, q2


def forward(q1, q2, l1, l2):
    return l1*cos(q1) + l2*cos(q1 + q2), l1*sin(q1) + l2*sin(q1 + q2)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("x", type=float)
    parser.add_argument("y", type=float)
    args = parser.parse_args()
    l1, l2 = 1.44, 1.03
    for direction, branch in (("Down", 1), ("Up", -1)):
        solution = inverse(args.x, args.y, l1, l2, branch)
        if solution is None:
            print("Target out of reach.")
            break
        x, y = forward(*solution, l1, l2)
        residual = hypot(x - args.x, y - args.y)
        q1, q2 = map(degrees, solution)
        print(f"{direction:4}  q1={q1:7.2f}°  q2={q2:7.2f}°  tip error={residual:.2e}")


if __name__ == "__main__":
    main()
