Collect all of the edges in the component [perhaps make a unique copy so as not to ruin the original ?]
the iterate the edges and erase those which have different edge.start.position.z and edge.end.position.z - i.e the are not ‘flat’.
You have now erased the ‘vertical’ edges and need to process the rest…
In your example there are two faces left…
Assuming the bottom face is the one you want to keep, and it’s facing ‘down’ just find the face.normal.z>0 then erase it.
The remaining one face is left - you might want to use face.reverse! on it to flip it to face up - assuming it’s already facing ‘down’ ?