import FreeCAD as App
import FreeCAD.Console as Console

class GeometryUseCase:
    def __init__(self, document):
        self.document = document

    def is_valid_geometry(self, obj):
        return hasattr(obj, "Shape") and obj.Shape.Volume is not None

    def create_intersection_matrix(self):
        bodies = [obj for obj in self.document.Objects if self.is_valid_geometry(obj)]
        num_bodies = len(bodies)
        intersection_matrix = [[False for _ in range(num_bodies)] for _ in range(num_bodies)]

        for i in range(num_bodies):
            for j in range(i + 1, num_bodies):
                body1 = bodies[i]
                body2 = bodies[j]

                if body1.Shape.common(body2.Shape).Volume > 0:
                    intersection_matrix[i][j] = True
                    intersection_matrix[j][i] = True

                    if not hasattr(body1, "AllowIntersections") or not hasattr(body2, "AllowIntersections"):
                        Console.PrintWarning(
                            f"Пересечение между '{body1.Name}' и '{body2.Name}' без разрешения.\n"
                        )

        return intersection_matrix

    def create_contact_matrix(self):
        bodies = [obj for obj in self.document.Objects if self.is_valid_geometry(obj)]
        num_bodies = len(bodies)
        contact_matrix = [[False for _ in range(num_bodies)] for _ in range(num_bodies)]

        for i in range(num_bodies):
            for j in range(i + 1, num_bodies):
                body1 = bodies[i]
                body2 = bodies[j]

                if body1.Shape.common(body2.Shape).SurfaceArea > 0:
                    contact_matrix[i][j] = True
                    contact_matrix[j][i] = True

        return contact_matrix


doc = App.ActiveDocument
if doc is None:
    Console.PrintError("Нет активного документа в FreeCAD.\n")
else:
    use_case = GeometryUseCase(doc)

    intersection_matrix = use_case.create_intersection_matrix()
    Console.PrintMessage("Матрица пересечений:\n")
    for row in intersection_matrix:
        Console.PrintMessage(f"{row}\n")

    contact_matrix = use_case.create_contact_matrix()
    Console.PrintMessage("Матрица контактов:\n")
    for row in contact_matrix:
        Console.PrintMessage(f"{row}\n")
