How to automate deleting duplicate HealthKit entries?

I wrote some Swift code to fetch all sleep data.

It returned 15,342 entries of which only 10,557 are unique…

So almost 5K of duplicate entries?! :cry: