Rewrite _format_actions_usage to generate groups directly

copy of python issue 11874 fix

this makes the code more robust, especially with long wrappable usage,
and presense of [] and () in metavars