import json
import os

import FreeCAD as App


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


def value_snapshot(obj, property_name):
    return sorted(int(value) for value in getattr(obj, property_name))


def property_snapshot(document, obj, property_name):
    return {
        "value": value_snapshot(obj, property_name),
        "propertyTypeId": obj.getTypeIdOfProperty(property_name),
        "group": obj.getGroupOfProperty(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": bool(document.recompute()),
        "shape": {"applicable": hasattr(obj, "Shape")},
        "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects],
    }


def run_case(object_type_id, object_name, property_name, group, nominal):
    document = App.newDocument("PropertyIntegerSet" + object_name)
    try:
        obj = document.addObject(object_type_id, object_name)
        # FreeCAD 1.1.1 can terminate when its never-assigned empty std::set binding is read.
        setattr(obj, property_name, [])
        phases = {"explicitEmpty": property_snapshot(document, obj, property_name)}
        values = {
            "deduplicated": nominal,
            "negativeBoundary": [-2, 0, 5],
            "scalar": 7,
            "largeSafeInteger": [9007199254740991],
            "restored": [],
        }
        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,
            "group": group,
            "mode": "direct-native-property-setter",
            "phases": phases,
        }
    finally:
        App.closeDocument(document.Name)


cases = [
    run_case("Fem::FemSetNodesObject", "NodesProbe", "Nodes", "Node indexes", [3, 1, 3, 2]),
    run_case("Fem::FemSetElementNodesObject", "ElementsProbe", "Elements", "Element indexes", [10, 4, 10]),
]
report = {
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-integerset-success",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "propertyType": "App::PropertyIntegerSet",
    "caseCount": len(cases),
    "bindingBoundary": {"neverAssignedEmptyRead": "native-process-termination", "safeEquivalent": "assign-empty-list-before-read", "oracleDefault": "set()"},
    "cases": cases,
}
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_INTEGERSET_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_INTEGERSET_SUCCESS_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))

