import json
import os

import FreeCAD as App


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


def color_list_value(obj):
    return [[round(float(channel), 9) for channel in color] for color in obj.ColourList]


def object_set(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 state_snapshot(obj):
    return {"state": [str(item) for item in obj.State], "statusString": str(obj.getStatusString())}


def run():
    document = App.newDocument("PropertyColorListFailure")
    try:
        obj = document.addObject("App::FeatureTest", "ColorListProbe")
        document.recompute()
        document.UndoMode = 1
        baseline_request = [0x11223344, 0xFFFFFFFF]
        obj.ColourList = baseline_request
        document.recompute()
        initial = color_list_value(obj)
        initial_objects = object_set(document)

        coercions = []
        for case_id, requested in [
            ("boolean-scalar", True),
            ("bytes-sequence", bytes([1, 255])),
            ("bare-float-tuple", (0.1, 0.2, 0.3, 0.4)),
            ("bare-integer-tuple", (255, 128, 0, 64)),
            ("tuple-packed-sequence", (0x11223344, 0xFFFFFFFF)),
            ("empty-dictionary", {}),
        ]:
            before = color_list_value(obj)
            before_objects = object_set(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "ColourList", value))
            after = color_list_value(obj)
            after_objects = object_set(document)
            coercions.append({
                "id": case_id,
                "requested": repr(requested),
                "exception": exception,
                "accepted": exception is None,
                "before": before,
                "after": after,
                "valuePreserved": before == after,
                "beforeObjects": before_objects,
                "afterObjects": after_objects,
                "objectsPreserved": before_objects == after_objects,
            })
            obj.ColourList = baseline_request

        failures = []
        for case_id, requested in [
            ("none", None),
            ("bare-float-list", [0.1, 0.2, 0.3, 0.4]),
            ("bare-mixed-tuple", (0.1, 2, 0.3)),
            ("nested-short-tuple", [(0.1, 0.2)]),
            ("mixed-valid-none", [(0.1, 0.2, 0.3, 0.4), None]),
            ("scalar-float", 0.5),
            ("string-sequence", "rgb"),
            ("nested-list", [[0.1, 0.2, 0.3, 0.4]]),
            ("dictionary-string-key", {"0": 0x11223344}),
            ("dictionary-high-index", {3: 0x11223344}),
            ("dictionary-negative-index", {-2: 0x11223344}),
            ("dictionary-partial-invalid", {0: 0x01020304, 1: None}),
        ]:
            obj.ColourList = baseline_request
            before = color_list_value(obj)
            before_objects = object_set(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "ColourList", value))
            after = color_list_value(obj)
            after_objects = object_set(document)
            failures.append({
                "id": case_id,
                "requested": repr(requested),
                "exception": exception,
                "before": before,
                "after": after,
                "valuePreserved": before == after,
                "beforeObjects": before_objects,
                "afterObjects": after_objects,
                "objectsPreserved": before_objects == after_objects,
                "polluted": before_objects != after_objects,
            })

        obj.ColourList = baseline_request
        disabled_before = color_list_value(obj)
        disabled_objects_before = object_set(document)
        obj.setEditorMode("ColourList", ["ReadOnly"])
        editor_mode = [str(item) for item in obj.getEditorMode("ColourList")]
        editor_requested = [(0.2, 0.3, 0.4, 0.5)]
        editor_read_only_exception = exception_snapshot(lambda: setattr(obj, "ColourList", editor_requested))
        editor_read_only_after = color_list_value(obj)
        obj.ColourList = baseline_request
        obj.setPropertyStatus("ColourList", "Immutable")
        immutable_status = [str(item) for item in obj.getPropertyStatus("ColourList")]
        immutable_exception = exception_snapshot(lambda: setattr(obj, "ColourList", [(0.6, 0.7, 0.8, 0.9)]))
        immutable_after = color_list_value(obj)
        obj.setPropertyStatus("ColourList", "-Immutable")
        obj.setEditorMode("ColourList", 0)
        disabled_objects_after = object_set(document)
        disabled = {
            "classification": "editor-readonly-python-mutable-until-immutable",
            "before": disabled_before,
            "editorMode": editor_mode,
            "editorReadOnlyRequested": [list(color) for color in editor_requested],
            "editorReadOnlyException": editor_read_only_exception,
            "editorReadOnlyAfter": editor_read_only_after,
            "pythonBypassesEditorReadOnly": editor_read_only_exception is None,
            "immutableStatus": immutable_status,
            "immutableRequested": [[0.6, 0.7, 0.8, 0.9]],
            "immutableException": immutable_exception,
            "immutableAfter": immutable_after,
            "immutableValuePreserved": initial == immutable_after,
            "restoredStatus": [str(item) for item in obj.getPropertyStatus("ColourList")],
            "restoredEditorMode": [str(item) for item in obj.getEditorMode("ColourList")],
            "objectsPreserved": disabled_objects_before == disabled_objects_after,
        }

        document.recompute()
        document.openTransaction("property-colorlist-cancel")
        transaction_before = color_list_value(obj)
        transaction_objects_before = object_set(document)
        obj.ColourList = [(0.75, 0.5, 0.25, 0.125), 0x11223344, (0, 255, 0, 128)]
        transaction_edited = color_list_value(obj)
        state_after_edit = state_snapshot(obj)
        pending_after_edit = bool(document.HasPendingTransaction)
        active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after_abort = color_list_value(obj)
        state_after_abort = state_snapshot(obj)
        recovery_recompute_result = bool(document.recompute())
        transaction_after_recompute = color_list_value(obj)
        state_after_recompute = state_snapshot(obj)
        transaction_objects_after = object_set(document)

        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-colorlist-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyColorList",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "ColourList", "typeId": obj.getTypeIdOfProperty("ColourList")},
            "initial": initial,
            "coercions": coercions,
            "failures": failures,
            "disabled": disabled,
            "transaction": {
                "before": transaction_before,
                "edited": transaction_edited,
                "afterAbort": transaction_after_abort,
                "afterRecompute": transaction_after_recompute,
                "stateAfterEdit": state_after_edit,
                "stateAfterAbort": state_after_abort,
                "stateAfterRecompute": state_after_recompute,
                "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(),
                "recoveryRecomputeResult": recovery_recompute_result,
                "restored": transaction_before == transaction_after_abort == transaction_after_recompute,
                "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": object_set(document), "objectsPreserved": initial_objects == object_set(document)},
        }
    finally:
        App.closeDocument(document.Name)


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