Bran told us exactly who the "legitimate heir" is...
Jon Snow, Aegon VII Targaryen
The line of succession always favors males and always favors children of the heir before siblings of the monarch.
Further reading: Comprehensive Rules for Game of Thrones Lines of Succession
The line of succession goes like this:
- Aerys "The Mad King" - "current" monarch, now deceased
- Rhaeghar - by rights as the first born son of Aerys, now deceased
- Aegon VI - by rights as the first born son Rhaeghar, now deceased
- Aegon VII (aka Jon Snow) - by right as the second born son of Rhaegar, alive!
The female line only comes into play once all male heirs are deceased, which is the crux of Danaerys' claim once her brother Viserys died. However, Viserys' claim was only considered valid because there were no other heirs (Rhaeghar and his line).
This was why Rhaegar's annulment was so important. If Rhaegar had still be married to Elia Martell, Jon Snow would still have been a bastard (assuming all other parties lived). This is why Bran initial says Jon is not a Snow but rather a Sand. The annulment make Jon a true-born heir and transforms him from Jon Snow to Aegon VII Targaryen.