Buy a utility designed for that sort of thing? Which I'm sure is not what you wanted to hear.
You'd need to dig into the macOS at a level lower than Keyboard Maestro does to perform that sort of job really well.
I've seen a few mouse drivers and other utilities over the years that were adept at this – but I'm not keeping track of utilities the way I used to and I don't presently have any favs.
This one came up on a cursory Google search and is inexpensive:
If I was going to buy such a thing I'd do a much more intensive search of course.