import hashlib
import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_BOOLLIST_MUTATION_OUTPUT", "")


def object_snapshot(document):
    return [{"name": obj.Name, "typeId": obj.TypeId} for obj in document.Objects]


def shape_snapshot(obj):
    if not hasattr(obj, "Shape"):
        return {"applicable": False, "reason": "host-has-no-shape-property"}
    shape = obj.Shape
    if shape.isNull():
        return {"applicable": True, "isNull": True, "shapeType": "Null", "solids": 0, "faces": 0, "edges": 0, "vertices": 0}
    brep = shape.exportBrepToString().encode("utf-8")
    bounds = shape.BoundBox
    return {
        "applicable": True,
        "isNull": False,
        "valid": bool(shape.isValid()),
        "shapeType": shape.ShapeType,
        "solids": len(shape.Solids),
        "faces": len(shape.Faces),
        "edges": len(shape.Edges),
        "vertices": len(shape.Vertexes),
        "area": round(float(shape.Area), 9),
        "volume": round(float(shape.Volume), 9),
        "bounds": [round(float(value), 9) for value in (bounds.XMin, bounds.YMin, bounds.ZMin, bounds.XMax, bounds.YMax, bounds.ZMax)],
        "brepSha256": hashlib.sha256(brep).hexdigest(),
    }


def phase_snapshot(document, obj, property_name):
    return {
        "value": list(getattr(obj, property_name)),
        "propertyTypeId": obj.getTypeIdOfProperty(property_name),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus(property_name)],
        "editorMode": [str(item) for item in obj.getEditorMode(property_name)],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "mustExecute": bool(obj.MustExecute),
        "shape": shape_snapshot(obj),
        "objectSet": object_snapshot(document),
    }


def direct_mutation(object_type_id, object_name, property_name, edited_value, setup_surface=False):
    document = App.newDocument("PropertyBoolList" + object_name + "Mutation")
    try:
        obj = document.addObject(object_type_id, object_name)
        if setup_surface:
            import Part
            points = [App.Vector(0, 0, 0), App.Vector(10, 0, 0), App.Vector(10, 10, 0), App.Vector(0, 10, 0)]
            boundaries = []
            for index in range(4):
                edge = document.addObject("Part::Feature", "Boundary" + str(index + 1))
                edge.Shape = Part.makeLine(points[index], points[(index + 1) % 4])
                boundaries.append((edge, ["Edge1"]))
            obj.BoundaryList = boundaries
        document.recompute()
        before = phase_snapshot(document, obj, property_name)
        setattr(obj, property_name, edited_value)
        touched_after_edit = phase_snapshot(document, obj, property_name)
        edit_recompute = bool(document.recompute())
        edited = phase_snapshot(document, obj, property_name)
        setattr(obj, property_name, before["value"])
        touched_after_restore = phase_snapshot(document, obj, property_name)
        restore_recompute = bool(document.recompute())
        restored = phase_snapshot(document, obj, property_name)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": property_name,
            "mode": "direct-native-property-setter",
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "before": before,
            "touchedAfterEdit": touched_after_edit,
            "editRecompute": edit_recompute,
            "edited": edited,
            "touchedAfterRestore": touched_after_restore,
            "restoreRecompute": restore_recompute,
            "restored": restored,
            "valueRestored": before["value"] == restored["value"],
            "shapeRestored": before["shape"] == restored["shape"],
            "objectsRestored": before["objectSet"] == restored["objectSet"],
        }
    finally:
        App.closeDocument(document.Name)


def link_mutation(object_type_id, object_name):
    document = App.newDocument("PropertyBoolList" + object_name + "Mutation")
    try:
        first = document.addObject("Part::Feature", "TargetA")
        second = document.addObject("Part::Feature", "TargetB")
        group = document.addObject("App::DocumentObjectGroup", "TargetGroup")
        group.addObjects([first, second])
        obj = document.addObject(object_type_id, object_name)
        if "LinkedObject" in obj.PropertiesList:
            obj.LinkedObject = group
            setup_property = "LinkedObject"
        else:
            obj.ElementList = [first, second]
            setup_property = "ElementList"
        document.recompute()
        before = phase_snapshot(document, obj, "VisibilityList")
        hide_result = int(obj.setElementVisible(first.Name, False))
        touched_after_edit = phase_snapshot(document, obj, "VisibilityList")
        edit_recompute = bool(document.recompute())
        edited = phase_snapshot(document, obj, "VisibilityList")
        show_result = int(obj.setElementVisible(first.Name, True))
        touched_after_restore = phase_snapshot(document, obj, "VisibilityList")
        restore_recompute = bool(document.recompute())
        restored = phase_snapshot(document, obj, "VisibilityList")
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": "VisibilityList",
            "mode": "link-base-extension-element-visibility",
            "setupProperty": setup_property,
            "hideResult": hide_result,
            "showResult": show_result,
            "before": before,
            "touchedAfterEdit": touched_after_edit,
            "editRecompute": edit_recompute,
            "edited": edited,
            "touchedAfterRestore": touched_after_restore,
            "restoreRecompute": restore_recompute,
            "restored": restored,
            "valueRestored": before["value"] == restored["value"],
            "shapeRestored": before["shape"] == restored["shape"],
            "objectsRestored": before["objectSet"] == restored["objectSet"],
        }
    finally:
        App.closeDocument(document.Name)


cases = [
    direct_mutation("App::FeatureTest", "FeatureTestProbe", "BoolList", [True, False, True]),
    direct_mutation("App::FeatureTestException", "FeatureTestExceptionProbe", "BoolList", [True, False, True]),
    direct_mutation("Surface::GeomFillSurface", "GeomFillSurfaceProbe", "ReversedList", [True, False, False, False], True),
    link_mutation("App::Link", "LinkProbe"),
    link_mutation("App::LinkGroup", "LinkGroupProbe"),
    link_mutation("App::LinkGroupPython", "LinkGroupPythonProbe"),
    link_mutation("App::LinkPython", "LinkPythonProbe"),
]
report = {
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-boollist-mutation",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "propertyType": "App::PropertyBoolList",
    "caseCount": len(cases),
    "cases": cases,
}
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_BOOLLIST_MUTATION_OUTPUT is required")
with open(OUTPUT_PATH, "w", encoding="utf-8") as handle:
    json.dump(report, handle, indent=2, sort_keys=True)
    handle.write("\n")
print("FREECAD_PROPERTY_BOOLLIST_MUTATION_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))
