Time ago I had the same problem and this script worked, this time is failing to recognize some points and I’m really having a bad time trying to do by myself, I can get an interpolate curve from those points.

I will really appreciate if someone give a little explanation of what is happening here.

Better to check first that the items to be connected from the original list are arranged in the correct order.
Check that the sort key you used is valid for organizing the order…

A good thing is to study Math, I have no best way, to be engineer in France you have to eat math for 2 years and I forgot most of what I learned (it was 28 years ago).
Try to learn the basics in geometry, vectors, cross (rule of the 3 fingers …) and dot product.
Follow the flow of information, step by step…

Here all the lines have not a consistant direction between each other. So I used cross product to have a sort of “North” or “South”. If south flip the curve. In order to get a consistant direction I used the vector made by mid points, they give me the direction of the curve you want, the line direction gave me a lateral direction (right or left), cross product gave me North (up or Z) South (down or -Z) …