import json
import os

import FreeCAD as App


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


def color_value(obj):
    return [round(float(channel), 9) for channel in obj.Colour]


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("PropertyColorFailure")
    try:
        obj = document.addObject("App::FeatureTest", "ColorProbe")
        document.recompute()
        document.UndoMode = 1
        initial = color_value(obj)
        initial_objects = object_set(document)

        coercions = []
        for case_id, requested in [
            ("float-out-of-range", (2.0, -1.0, 0.5, 1.5)),
            ("integer-out-of-range", (-1, 256, 511, -255)),
            ("boolean-tuple", (True, False, True, False)),
            ("packed-max", 0xFFFFFFFF),
            ("packed-wrap", 0x100000000),
            ("packed-negative", -1),
        ]:
            before = color_value(obj)
            before_objects = object_set(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "Colour", value))
            after = color_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,
            })
            if exception is None:
                obj.Colour = tuple(initial)

        failures = []
        for case_id, requested in [
            ("none", None),
            ("list", [0.1, 0.2, 0.3]),
            ("short-tuple", (0.1, 0.2)),
            ("long-tuple", (0.1, 0.2, 0.3, 0.4, 0.5)),
            ("string-first", ("bad", 0.2, 0.3)),
            ("mixed-after-float", (0.1, 2, 0.3)),
            ("mixed-after-integer", (1, 0.2, 3)),
            ("scalar-float", 0.5),
        ]:
            before = color_value(obj)
            before_objects = object_set(document)
            exception = exception_snapshot(lambda value=requested: setattr(obj, "Colour", value))
            after = color_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,
            })
            if exception is None:
                obj.Colour = tuple(initial)

        disabled_before = color_value(obj)
        disabled_objects_before = object_set(document)
        obj.setEditorMode("Colour", ["ReadOnly"])
        editor_mode = [str(item) for item in obj.getEditorMode("Colour")]
        editor_read_only_exception = exception_snapshot(lambda: setattr(obj, "Colour", (0.2, 0.3, 0.4, 0.5)))
        editor_read_only_after = color_value(obj)
        obj.Colour = tuple(initial)
        obj.setPropertyStatus("Colour", "Immutable")
        immutable_status = [str(item) for item in obj.getPropertyStatus("Colour")]
        immutable_exception = exception_snapshot(lambda: setattr(obj, "Colour", (0.6, 0.7, 0.8, 0.9)))
        immutable_after = color_value(obj)
        obj.setPropertyStatus("Colour", "-Immutable")
        obj.setEditorMode("Colour", 0)
        disabled_objects_after = object_set(document)
        disabled = {
            "classification": "editor-readonly-python-mutable-until-immutable",
            "before": disabled_before,
            "editorMode": editor_mode,
            "editorReadOnlyRequested": [0.2, 0.3, 0.4, 0.5],
            "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("Colour")],
            "restoredEditorMode": [str(item) for item in obj.getEditorMode("Colour")],
            "objectsPreserved": disabled_objects_before == disabled_objects_after,
        }

        document.recompute()
        document.openTransaction("property-color-cancel")
        transaction_before = color_value(obj)
        transaction_objects_before = object_set(document)
        obj.Colour = (0.75, 0.5, 0.25, 0.125)
        transaction_edited = color_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_value(obj)
        state_after_abort = state_snapshot(obj)
        recovery_recompute_result = bool(document.recompute())
        transaction_after_recompute = color_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-color-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyColor",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "Colour", "typeId": obj.getTypeIdOfProperty("Colour")},
            "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_COLOR_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_COLOR_FAILURE_RESULT=" + json.dumps({"status": report["status"], "coercionCount": len(report["coercions"]), "failureCount": len(report["failures"])}, sort_keys=True))
