The issue is not with your logic — it is because Pyrogram does not automatically preserve caption entities when you manually rebuild a media group.
When you extract messages from chat history using:
await client.get_chat_history(...)
Pyrogram gives you:
message.caption
message.caption_entities
BUT entities are NOT applied automatically when you create new InputMediaPhoto / InputMediaVideo.
InputMediaPhoto and InputMediaVideo require you to explicitly pass the entities if you want them preserved.
You are only sending:
caption=m.caption
So the entities are lost.