import json
import os

import FreeCAD as App


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


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}
    return {
        "applicable": True,
        "isNull": False,
        "shapeType": shape.ShapeType,
        "valid": bool(shape.isValid()),
        "solids": len(shape.Solids),
        "faces": len(shape.Faces),
        "edges": len(shape.Edges),
        "vertices": len(shape.Vertexes),
    }


def property_snapshot(document, obj, property_name):
    recompute_result = bool(document.recompute())
    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()),
        "recomputeResult": recompute_result,
        "shape": shape_snapshot(obj),
        "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects],
    }


def writable_case(object_type_id, object_name, property_name, valid_surface=False):
    document = App.newDocument("PropertyBoolList" + object_name)
    try:
        obj = document.addObject(object_type_id, object_name)
        if valid_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
        default_value = list(getattr(obj, property_name))
        phases = {"default": property_snapshot(document, obj, property_name)}
        values = ({
            "allFalse": [False, False, False, False],
            "oneReversed": [True, False, False, False],
            "alternating": [True, False, True, False],
            "allReversed": [True, True, True, True],
            "restored": default_value,
        } if valid_surface else {
            "empty": [],
            "singleton": [True],
            "mixed": [True, False, True, False],
            "large": [index % 3 == 0 for index in range(257)],
            "restored": default_value,
        })
        for phase, value in values.items():
            setattr(obj, property_name, value)
            phases[phase] = property_snapshot(document, obj, property_name)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": property_name,
            "mode": "direct-native-property-setter",
            "propertyAssignmentsAccepted": True,
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "defaultValue": default_value,
            "phases": phases,
        }
    finally:
        App.closeDocument(document.Name)


def link_case(object_type_id, object_name):
    document = App.newDocument("PropertyBoolList" + object_name)
    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"
        elif "Link" in obj.PropertiesList:
            obj.Link = group
            setup_property = "Link"
        elif "ElementList" in obj.PropertiesList:
            obj.ElementList = [first, second]
            setup_property = "ElementList"
        else:
            raise RuntimeError(object_type_id + " has no native Link input property")
        phases = {"linked": property_snapshot(document, obj, "VisibilityList")}
        hide_result = int(obj.setElementVisible(first.Name, False))
        phases["hidden"] = property_snapshot(document, obj, "VisibilityList")
        show_result = int(obj.setElementVisible(first.Name, True))
        phases["restored"] = property_snapshot(document, obj, "VisibilityList")
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": "VisibilityList",
            "mode": "link-base-extension-element-visibility",
            "propertyAssignmentsAccepted": True,
            "hostExecution": "normal",
            "setupProperty": setup_property,
            "hideResult": hide_result,
            "showResult": show_result,
            "phases": phases,
        }
    finally:
        App.closeDocument(document.Name)


cases = [
    writable_case("App::FeatureTest", "FeatureTestProbe", "BoolList"),
    writable_case("App::FeatureTestException", "FeatureTestExceptionProbe", "BoolList"),
    writable_case("Surface::GeomFillSurface", "GeomFillSurfaceProbe", "ReversedList", True),
    link_case("App::Link", "LinkProbe"),
    link_case("App::LinkGroup", "LinkGroupProbe"),
    link_case("App::LinkGroupPython", "LinkGroupPythonProbe"),
    link_case("App::LinkPython", "LinkPythonProbe"),
]
report = {
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-boollist-success",
    "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_SUCCESS_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_SUCCESS_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))
