import json

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
INVALID_INPUTS = [("wrong-dimension", "5 mm"), ("malformed-text", "not-a-quantity")]


def value_snapshot(obj, property_name):
    value = getattr(obj, property_name)
    return {"raw": str(value), "numeric": round(float(value.Value), 9), "unit": str(value.Unit)}


def object_snapshot(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()
    if not active:
        return {"name": "", "id": 0}
    return {"name": str(active[0]), "id": int(active[1])}


def run():
    document = App.newDocument("PropertyHeatFluxFailure")
    try:
        obj = document.addObject("Fem::ConstraintHeatflux", "HeatFluxProbe")
        document.recompute()
        document.UndoMode = 1
        initial = value_snapshot(obj, "DFlux")
        initial_objects = object_snapshot(document)
        failures = []
        for case_id, requested in INVALID_INPUTS:
            before = value_snapshot(obj, "DFlux")
            before_objects = object_snapshot(document)
            exception = exception_snapshot(lambda: setattr(obj, "DFlux", requested))
            after = value_snapshot(obj, "DFlux")
            after_objects = object_snapshot(document)
            failures.append({
                "id": case_id,
                "requested": 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 = value_snapshot(obj, "DFlux")
        disabled_objects_before = object_snapshot(document)
        obj.setEditorMode("DFlux", ["ReadOnly"])
        obj.setPropertyStatus("DFlux", "Immutable")
        disabled_status = [str(item) for item in obj.getPropertyStatus("DFlux")]
        disabled_editor_mode = [str(item) for item in obj.getEditorMode("DFlux")]
        disabled_exception = exception_snapshot(lambda: setattr(obj, "DFlux", "750 W/m^2"))
        disabled_after = value_snapshot(obj, "DFlux")
        disabled_objects_after = object_snapshot(document)
        obj.setPropertyStatus("DFlux", "-Immutable")
        obj.setEditorMode("DFlux", 0)

        document.openTransaction("property-heatflux-cancel")
        transaction_before = value_snapshot(obj, "DFlux")
        transaction_objects_before = object_snapshot(document)
        obj.DFlux = "250 W/m^2"
        transaction_edited = value_snapshot(obj, "DFlux")
        transaction_pending_after_edit = bool(document.HasPendingTransaction)
        transaction_active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after = value_snapshot(obj, "DFlux")
        transaction_objects_after = object_snapshot(document)
        final_objects = object_snapshot(document)
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-heatflux-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "DFlux", "typeId": obj.getTypeIdOfProperty("DFlux")},
            "initial": initial,
            "failures": failures,
            "disabled": {
                "classification": "editor-read-only-and-python-immutable",
                "requested": "750 W/m^2",
                "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("DFlux")],
                "restoredEditorMode": [str(item) for item in obj.getEditorMode("DFlux")],
            },
            "transaction": {
                "before": transaction_before,
                "edited": transaction_edited,
                "afterAbort": transaction_after,
                "objectsBefore": transaction_objects_before,
                "objectsAfter": transaction_objects_after,
                "undoMode": int(document.UndoMode),
                "pendingAfterEdit": transaction_pending_after_edit,
                "pendingAfterAbort": bool(document.HasPendingTransaction),
                "activeAfterEdit": transaction_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": final_objects, "objectsPreserved": initial_objects == final_objects, "objectCount": len(final_objects)},
        }
    finally:
        App.closeDocument(document.Name)


print("FREECAD_PROPERTY_HEATFLUX_FAILURE_RESULT=" + json.dumps(run(), sort_keys=True))

