How to get a line in group a that intersects or approaches a line in group B through rtree ?

here have 2 sets of lines, group a and group B,
I want to find the line that intersects the B group from the a group line. When it does not intersect, I will find the nearest line (need to exclude the lines that have already intersected).

When the number of lines is relatively large, the conventional method of looping will be very slow. I want to use the rtree method, does anyone who can tell me how to write the code.

thanks!

test1.3dm (94.5 KB)

test1.gh (11.5 KB)

One way to use RTree is:
1.to divide lines in both groups, A and B, (divide = create dividing points) with some equidistant segment length, Lets call this segment length S.
2. create rtree from group B dividing points, including end points of every line
3. Now if we consider two lines LineA and LineB, whose closest points are at distance D (distance btw theese two lines) then we know that there must be a pair of dividing points (pAi, pBj) whose distance is less or equal to:
SQRT( (0.5 * S) * (0.5 * S) + (0.5 * S) * (0.5 * S) + D * D) = SQRT( 0.5 * S * S + D * D).
This value will be radius of our sphere used for rtree search.
4.LineA can intersect more then one LinesB. But if there is no intersection then only one closest LineB will be selected (even if there can be more LinesB that are on same distance from LineA)

LinesA_LinesB_Intersect_V1.gh (560.3 KB)

thanks Radovan .