It is an interesting problem in programming. OK, you can't look at the music or the key signature. Can you get your program to look only at the last chord? If so, that is very likely to be the tonic chord in the key the piece was in. The exceptions will probably be more modern pieces with which any program you write will have trouble anyway.
If you want to ask the question "What is the dominant tonality in a given interval of time in this piece?" based on the frequency with which notes are struck during that interval, then I think it really is a very interesting programming problem. I think that you would need to do neural nets rather than a straightforward counting program.
So if you want the key of the piece as a whole and can get the software to focus on the final chord, then it's almost trivial, with due allowance for the Tierce de Picardy (which is the situation in which a piece in a minor key has a final chord in the corresponding major key, E minor-E major, for example). On the other hand, if you want to train a computer to recognize what tonality a piece is in at any given moment, then that's a cool but difficult problem.