import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_COLORLIST_SUCCESS_OUTPUT", "")
HOSTS = [
    ("App::FeatureTest", "FeatureTestColorListProbe"),
    ("App::FeatureTestException", "FeatureTestExceptionColorListProbe"),
]


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


def snapshot(document, obj):
    recompute_result = bool(document.recompute())
    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()),
        "recomputeResult": recompute_result,
        "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)
        default_value = color_list_value(obj)
        phases = {"default": snapshot(document, obj)}

        obj.ColourList = []
        phases["empty"] = snapshot(document, obj)
        obj.ColourList = [(0.25, 0.5, 0.75)]
        phases["singletonFloat"] = snapshot(document, obj)
        obj.ColourList = [(0.1, 0.2, 0.3, 0.4), (255, 128, 0, 64), 0x11223344]
        phases["mixedElements"] = snapshot(document, obj)
        obj.ColourList = 0x11223344
        phases["singlePacked"] = snapshot(document, obj)
        obj.ColourList = (color for color in [(0.0, 0.25, 0.5, 0.75), (1.0, 0.75, 0.5, 0.25)])
        phases["iterable"] = snapshot(document, obj)
        obj.ColourList = [(0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)]
        obj.ColourList = {1: 0x11223344, -1: (0, 255, 0, 128)}
        phases["indexedDictionary"] = snapshot(document, obj)
        obj.ColourList = [0x01020304] * 257
        phases["largeList"] = snapshot(document, obj)
        obj.ColourList = [tuple(color) for color in default_value]
        phases["restored"] = snapshot(document, obj)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": "ColourList",
            "mode": "native-property-list-setter",
            "propertyAssignmentsAccepted": True,
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "defaultValue": default_value,
            "phases": phases,
        }
    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-success",
    "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_SUCCESS_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_SUCCESS_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))
