If I had to guess at one thing I would say check Ground E15 near the battery.
Reasoning for that is, it is a common site for collision repair and an easy ground to compromise. If the ground is there but loose/dirty/or painted over it may have enough contact to power the circuit within the transmission that is causing the car to go into fail safe when the headlights are off but when they are on it does not have enough contact to complete the circuit. In some cars you may notice the headlights were dim or something weird like that.
I am assuming the battery is connected properly and is in top working order.
Is the check engine light or AT check light on?