import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_COLORLIST_MUTATION_OUTPUT", "")
TARGET = [(0.125, 0.375, 0.625, 0.875), 0x11223344, (255, 0, 128, 64), (0.0, 0.0, 0.0, 0.0)]
HOSTS = [
    ("App::FeatureTest", "FeatureTestColorListMutation"),
    ("App::FeatureTestException", "FeatureTestExceptionColorListMutation"),
]


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


def snapshot(document, obj):
    return {
        "value": color_list_value(obj),
        "propertyTypeId": obj.getTypeIdOfProperty("ColourList"),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("ColourList")],
        "editorMode": [str(item) for item in obj.getEditorMode("ColourList")],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "shape": {"applicable": False, "reason": "host-has-no-shape-property"} if "Shape" not in obj.PropertiesList else {"applicable": True},
        "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects],
    }


def run_case(object_type_id, object_name):
    document = App.newDocument("PropertyColorList" + object_name)
    try:
        obj = document.addObject(object_type_id, object_name)
        document.recompute()
        before = snapshot(document, obj)
        original = [tuple(color) for color in before["value"]]
        obj.ColourList = TARGET
        touched_after_edit = snapshot(document, obj)
        edit_recompute_result = bool(document.recompute())
        edited = snapshot(document, obj)
        obj.ColourList = original
        touched_after_restore = snapshot(document, obj)
        restore_recompute_result = bool(document.recompute())
        restored = snapshot(document, obj)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": "ColourList",
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "target": [list(value) if isinstance(value, tuple) else value for value in TARGET],
            "before": before,
            "touchedAfterEdit": touched_after_edit,
            "edited": edited,
            "touchedAfterRestore": touched_after_restore,
            "restored": restored,
            "editRecomputeResult": edit_recompute_result,
            "restoreRecomputeResult": restore_recompute_result,
            "mutationDetected": before["value"] != edited["value"],
            "restoredExactly": before["value"] == restored["value"] and before["objectSet"] == restored["objectSet"] and before["shape"] == restored["shape"],
        }
    finally:
        App.closeDocument(document.Name)


cases = [run_case(*host) for host in HOSTS]
report = {
    "schemaVersion": 1,
    "status": "pass",
    "baselineId": "freecad-1.1.1-property-colorlist-mutation",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "propertyType": "App::PropertyColorList",
    "caseCount": len(cases),
    "cases": cases,
}
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_COLORLIST_MUTATION_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_MUTATION_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"], "restored": sum(1 for case in cases if case["restoredExactly"])}, sort_keys=True))
