This is my first comment on HN. I wrote some algorithms to do with this topic. I've been working on some code for a long time which looks at the c=2^12 combinations of notes, their properties and so on. I call each of them changes. I'm actually still working on material for a book which contains dynamically generated layouts based on these changes. So far I have addressed many music set theory properties, as well as some visualisation on different instruments like piano, fretboard (arbitrary).
One of the algorithms looks at finding the most efficient enharmonic spelling for a given change.. It may be helpful. If anything you could look at the Python for that function and derive something suitable.. Feel free to PM..
Let's say that keys = 12, and changes = 2^12.. so you'd have 48152 possible key changes.. for each of these there are basically three enharmonic roots.. The you could multiply that by the potential variation within the scale degrees. If you just brute force that you'd essentially just keep the one with fewest accidentals
Super interested in this, could you please contact me via jacques@modularcompany.com? (your profile is not filled out for me so I don't know your email address, note that HN has the option to add a public email address as well in your profile but for you that is still blank).