import json
import os

import FreeCAD as App


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


def values(obj):
    return sorted(int(value) for value in obj.Nodes)


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


def exception_snapshot(callback):
    try:
        callback()
    except Exception as error:
        return {"type": type(error).__name__, "message": str(error)}
    return None


def active_transaction_snapshot():
    active = App.getActiveTransaction()
    return {"name": str(active[0]), "id": int(active[1])} if active else {"name": "", "id": 0}


def run():
    document = App.newDocument("PropertyIntegerSetFailure")
    try:
        obj = document.addObject("Fem::FemSetNodesObject", "NodesProbe")
        obj.Nodes = [1, 3]
        document.recompute()
        document.UndoMode = 1
        initial = values(obj)
        initial_objects = objects(document)
        failures = []
        for case_id, requested in [("float-item", [1, 1.5]), ("string-item", [1, "3"]), ("set-object", {1, 3}), ("none", None)]:
            before = values(obj)
            before_objects = objects(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "Nodes", value))
            after = values(obj)
            after_objects = objects(document)
            failures.append({"id": case_id, "requested": repr(requested), "exception": exception, "before": before, "after": after, "beforeObjects": before_objects, "afterObjects": after_objects, "valuePreserved": before == after, "objectsPreserved": before_objects == after_objects, "polluted": before_objects != after_objects})

        disabled_before = values(obj)
        disabled_objects_before = objects(document)
        obj.setEditorMode("Nodes", ["ReadOnly"])
        obj.setPropertyStatus("Nodes", "Immutable")
        disabled_status = [str(item) for item in obj.getPropertyStatus("Nodes")]
        disabled_editor_mode = [str(item) for item in obj.getEditorMode("Nodes")]
        disabled_exception = exception_snapshot(lambda: setattr(obj, "Nodes", [2, 4]))
        disabled_after = values(obj)
        disabled_objects_after = objects(document)
        obj.setPropertyStatus("Nodes", "-Immutable")
        obj.setEditorMode("Nodes", 0)

        document.openTransaction("property-integerset-cancel")
        transaction_before = values(obj)
        transaction_objects_before = objects(document)
        obj.Nodes = [2, 4, 4]
        transaction_edited = values(obj)
        pending_after_edit = bool(document.HasPendingTransaction)
        active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after = values(obj)
        transaction_objects_after = objects(document)
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-integerset-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyIntegerSet",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "Nodes", "typeId": obj.getTypeIdOfProperty("Nodes")},
            "initial": initial,
            "failures": failures,
            "disabled": {"classification": "editor-read-only-and-python-immutable", "requested": [2, 4], "status": disabled_status, "editorMode": disabled_editor_mode, "exception": disabled_exception, "before": disabled_before, "after": disabled_after, "valuePreserved": disabled_before == disabled_after, "objectsPreserved": disabled_objects_before == disabled_objects_after, "restoredStatus": [str(item) for item in obj.getPropertyStatus("Nodes")], "restoredEditorMode": [str(item) for item in obj.getEditorMode("Nodes")]},
            "transaction": {"before": transaction_before, "edited": transaction_edited, "afterAbort": transaction_after, "objectsBefore": transaction_objects_before, "objectsAfter": transaction_objects_after, "undoMode": int(document.UndoMode), "pendingAfterEdit": pending_after_edit, "pendingAfterAbort": bool(document.HasPendingTransaction), "activeAfterEdit": active_after_edit, "activeAfterAbort": active_transaction_snapshot(), "restored": transaction_before == transaction_after, "objectsRestored": transaction_objects_before == transaction_objects_after},
            "cancellationBoundary": {"supported": False, "classification": "synchronous-property-setter", "reason": "no-native-cancel-hook", "replacement": "abort-active-document-transaction"},
            "documentIntegrity": {"initialObjects": initial_objects, "finalObjects": objects(document), "objectsPreserved": initial_objects == objects(document)},
        }
    finally:
        App.closeDocument(document.Name)


report = run()
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_INTEGERSET_FAILURE_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_FAILURE_RESULT=" + json.dumps({"status": report["status"], "failureCount": len(report["failures"])}, sort_keys=True))

