The lineinfile task has to match both the commented and uncommented state of the line. This way it will uncomment #lego but will pass lego unchanged.
This task should do what you want:
- name: test lineinfile
lineinfile:
backup=yes
state=present
dest=/etc/foo.txt
regexp='^#?lego'
line='lego'