import json
import os

import FreeCAD as App


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


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


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


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


def writable_failures():
    document = App.newDocument("PropertyBoolListFailure")
    try:
        obj = document.addObject("App::FeatureTest", "BoolListProbe")
        document.recompute()
        document.UndoMode = 1
        initial = list(obj.BoolList)
        initial_objects = object_snapshot(document)
        accepted_coercions = []
        for case_id, requested in [("scalar-integer", 7), ("bitstring", "10201")]:
            before = list(obj.BoolList)
            before_objects = object_snapshot(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "BoolList", value))
            after = list(obj.BoolList)
            after_objects = object_snapshot(document)
            accepted_coercions.append({
                "id": case_id,
                "requested": repr(requested),
                "exception": exception,
                "before": before,
                "after": after,
                "beforeObjects": before_objects,
                "afterObjects": after_objects,
                "objectsPreserved": before_objects == after_objects,
            })
            obj.BoolList = initial
        requested_cases = [
            ("none", None),
            ("float-item", [True, 1.5]),
            ("string-item", [False, "bad"]),
        ]
        failures = []
        for case_id, requested in requested_cases:
            before = list(obj.BoolList)
            before_objects = object_snapshot(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "BoolList", value))
            after = list(obj.BoolList)
            after_objects = object_snapshot(document)
            if exception is None:
                obj.BoolList = initial
            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 = list(obj.BoolList)
        disabled_objects_before = object_snapshot(document)
        obj.setEditorMode("BoolList", ["ReadOnly"])
        obj.setPropertyStatus("BoolList", "Immutable")
        disabled_status = [str(item) for item in obj.getPropertyStatus("BoolList")]
        disabled_editor_mode = [str(item) for item in obj.getEditorMode("BoolList")]
        disabled_exception = exception_snapshot(lambda: setattr(obj, "BoolList", [True, False]))
        disabled_after = list(obj.BoolList)
        disabled_objects_after = object_snapshot(document)
        obj.setPropertyStatus("BoolList", "-Immutable")
        obj.setEditorMode("BoolList", 0)
        disabled = {
            "classification": "editor-read-only-and-python-immutable",
            "requested": [True, False],
            "status": disabled_status,
            "editorMode": disabled_editor_mode,
            "exception": disabled_exception,
            "before": disabled_before,
            "after": disabled_after,
            "beforeObjects": disabled_objects_before,
            "afterObjects": disabled_objects_after,
            "valuePreserved": disabled_before == disabled_after,
            "objectsPreserved": disabled_objects_before == disabled_objects_after,
            "restoredStatus": [str(item) for item in obj.getPropertyStatus("BoolList")],
            "restoredEditorMode": [str(item) for item in obj.getEditorMode("BoolList")],
        }

        document.openTransaction("property-boollist-cancel")
        transaction_before = list(obj.BoolList)
        transaction_objects_before = object_snapshot(document)
        obj.BoolList = [True, False, True]
        transaction_edited = list(obj.BoolList)
        pending_after_edit = bool(document.HasPendingTransaction)
        active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after = list(obj.BoolList)
        transaction_objects_after = object_snapshot(document)
        return {
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "BoolList", "typeId": obj.getTypeIdOfProperty("BoolList")},
            "initial": initial,
            "acceptedCoercions": accepted_coercions,
            "failures": failures,
            "disabled": disabled,
            "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,
            },
            "documentIntegrity": {
                "initialObjects": initial_objects,
                "finalObjects": object_snapshot(document),
                "objectsPreserved": initial_objects == object_snapshot(document),
            },
        }
    finally:
        App.closeDocument(document.Name)


def link_failure(object_type_id, object_name):
    document = App.newDocument("PropertyBoolList" + object_name + "Failure")
    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
        else:
            obj.ElementList = [first, second]
        document.recompute()
        document.UndoMode = 1
        initial = list(obj.VisibilityList)
        initial_objects = object_snapshot(document)
        direct_exception = exception_snapshot(lambda: setattr(obj, "VisibilityList", [False, True]))
        after_direct = list(obj.VisibilityList)
        invalid_element_result = int(obj.setElementVisible("MissingElement", False))
        after_invalid_element = list(obj.VisibilityList)
        document.openTransaction("property-boollist-link-cancel")
        transaction_before = list(obj.VisibilityList)
        hide_result = int(obj.setElementVisible(first.Name, False))
        transaction_edited = list(obj.VisibilityList)
        pending_after_edit = bool(document.HasPendingTransaction)
        active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after = list(obj.VisibilityList)
        state_after_abort = [str(item) for item in obj.State]
        status_after_abort = str(obj.getStatusString())
        recovery_recompute_result = bool(document.recompute())
        state_after_recovery = [str(item) for item in obj.State]
        status_after_recovery = str(obj.getStatusString())
        return {
            "objectTypeId": object_type_id,
            "propertyTypeId": obj.getTypeIdOfProperty("VisibilityList"),
            "initial": initial,
            "status": [str(item) for item in obj.getPropertyStatus("VisibilityList")],
            "editorMode": [str(item) for item in obj.getEditorMode("VisibilityList")],
            "directWrite": {"requested": [False, True], "exception": direct_exception, "after": after_direct, "preserved": initial == after_direct},
            "invalidElement": {"name": "MissingElement", "result": invalid_element_result, "after": after_invalid_element, "preserved": initial == after_invalid_element},
            "transaction": {
                "before": transaction_before,
                "hideResult": hide_result,
                "edited": transaction_edited,
                "afterAbort": transaction_after,
                "pendingAfterEdit": pending_after_edit,
                "pendingAfterAbort": bool(document.HasPendingTransaction),
                "activeAfterEdit": active_after_edit,
                "activeAfterAbort": active_transaction_snapshot(),
                "restored": transaction_before == transaction_after,
                "stateAfterAbort": state_after_abort,
                "statusAfterAbort": status_after_abort,
                "recoveryRecomputeResult": recovery_recompute_result,
                "stateAfterRecovery": state_after_recovery,
                "statusAfterRecovery": status_after_recovery,
            },
            "objectState": state_after_recovery,
            "statusString": status_after_recovery,
            "objectsBefore": initial_objects,
            "objectsAfter": object_snapshot(document),
            "objectsPreserved": initial_objects == object_snapshot(document),
        }
    finally:
        App.closeDocument(document.Name)


writable = writable_failures()
links = [
    link_failure("App::Link", "LinkProbe"),
    link_failure("App::LinkGroup", "LinkGroupProbe"),
    link_failure("App::LinkGroupPython", "LinkGroupPythonProbe"),
    link_failure("App::LinkPython", "LinkPythonProbe"),
]
report = {
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-boollist-failure",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "propertyType": "App::PropertyBoolList",
    "writable": writable,
    "links": links,
    "cancellationBoundary": {
        "supported": False,
        "classification": "synchronous-property-setter-and-link-extension",
        "reason": "no-native-cancel-hook",
        "replacement": "abort-active-document-transaction",
    },
}
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_BOOLLIST_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_BOOLLIST_FAILURE_RESULT=" + json.dumps({"status": report["status"], "failureCount": len(writable["failures"]), "linkCount": len(links)}, sort_keys=True))
