The split is phonetic, not semantic. なん appears before the た, だ and な rows — the sounds you make with your tongue against the ridge behind your top teeth — and before every counter. なに covers everything else. That is the whole rule, and it explains 何ですか against 何を without any appeal to politeness or formality.
Counters are the half that changes the meaning. 何時 is not what time in the sense of which hour is your favourite — it asks you to supply a number. Same with 何人, 何回, 何歳. When 何 is glued to a counter, translate it as how many and the sentence falls into place.
何で is two different words. Read なんで it means why, and it is casual — the neutral word is どうして or なぜ. Read なにで it means by what means: 何で行きますか, what are you going by. Same two characters, and only the reading tells them apart.
Adding か, も or でも switches it out of question mode. 何か is something, 何も is nothing and demands a negative verb, 何でも is anything at all. This is a pattern, not a set of three words — 誰, どこ and いつ all do the same thing with the same three particles.