I'm solving basically the same problem of "how do I map name+email address+password to IMAP and/or SMTP". Clearly, Thunderbird's got this one solved or near solved.
I can hunt through their source code, but is there any documentation on how this works?
You're probably looking for the account autoconfiguration documentation:
https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Autoconfiguration