"""Auto-imported patch (when this dir is on PYTHONPATH): make build123d 0.11's
Compound.center() robust. TOM's gen_urdf calls .center() on custom build123d
parts whose Compound nesting trips a `_wrapped is None` AssertionError in 0.11;
the true centroid is still recoverable by collapsing to a solids-only Compound,
else the bbox center. Logs each fallback so we learn which parts are affected.
Scoped: only active when tom_build.sh puts this dir on PYTHONPATH.
"""
import sys


def _patch() -> None:
    from build123d.topology.composite import Compound

    if getattr(Compound, "_tom_center_patched", False):
        return
    _orig = Compound.center

    def _safe_center(self, *args, **kwargs):
        try:
            return _orig(self, *args, **kwargs)
        except Exception as exc:
            try:
                solids = list(self.solids())
            except Exception:
                solids = []
            if solids:
                try:
                    from build123d import Compound as _C

                    val = _C(children=solids).center(*args, **kwargs)
                    sys.stderr.write(
                        f"[tom_patch] center(): solids-collapse fallback "
                        f"({len(solids)} solids) after {type(exc).__name__}\n"
                    )
                    return val
                except Exception:
                    pass
            bb = self.bounding_box()
            sys.stderr.write(
                f"[tom_patch] center(): bbox-center fallback after "
                f"{type(exc).__name__}\n"
            )
            return bb.center()

    Compound.center = _safe_center
    Compound._tom_center_patched = True


try:
    _patch()
    sys.stderr.write("[tom_patch] build123d Compound.center robustness patch active\n")
except Exception as _exc:  # never break interpreter startup
    sys.stderr.write(f"[tom_patch] patch failed: {_exc}\n")
