import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_COLOR_SUCCESS_OUTPUT", "")
HOSTS = [
    ("App::FeatureTest", "FeatureTestColorProbe", "Colour"),
    ("App::FeatureTestException", "FeatureTestExceptionColorProbe", "Colour"),
    ("App::Part", "PartColorProbe", "Color"),
    ("Assembly::AssemblyLink", "AssemblyLinkColorProbe", "Color"),
    ("Assembly::AssemblyObject", "AssemblyObjectColorProbe", "Color"),
    ("TechDraw::DrawViewAnnotation", "AnnotationColorProbe", "TextColor"),
    ("TechDraw::DrawViewDraft", "DraftColorProbe", "Color"),
    ("TechDraw::DrawViewSpreadsheet", "SpreadsheetColorProbe", "TextColor"),
]
ASSIGNMENTS = [
    ("floatRgb", (0.25, 0.5, 0.75)),
    ("floatRgba", (0.1, 0.2, 0.3, 0.4)),
    ("byteRgb", (1, 127, 255)),
    ("byteRgba", (255, 128, 0, 64)),
    ("packedRgba", 0x11223344),
    ("transparentBoundary", (0.0, 0.0, 0.0, 0.0)),
]


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


def shape_snapshot(obj):
    if not hasattr(obj, "Shape"):
        return {"applicable": False, "reason": "host-has-no-shape-property"}
    shape = obj.Shape
    if shape.isNull():
        return {"applicable": True, "isNull": True, "shapeType": "Null", "solids": 0, "faces": 0, "edges": 0, "vertices": 0}
    return {
        "applicable": True,
        "isNull": False,
        "shapeType": shape.ShapeType,
        "valid": bool(shape.isValid()),
        "solids": len(shape.Solids),
        "faces": len(shape.Faces),
        "edges": len(shape.Edges),
        "vertices": len(shape.Vertexes),
    }


def property_snapshot(document, obj, property_name):
    recompute_result = bool(document.recompute())
    return {
        "value": color_value(obj, property_name),
        "propertyTypeId": obj.getTypeIdOfProperty(property_name),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus(property_name)],
        "editorMode": [str(item) for item in obj.getEditorMode(property_name)],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "recomputeResult": recompute_result,
        "shape": shape_snapshot(obj),
        "objectSet": [{"name": candidate.Name, "typeId": candidate.TypeId} for candidate in document.Objects],
    }


def run_case(object_type_id, object_name, property_name):
    document = App.newDocument("PropertyColor" + object_name)
    try:
        obj = document.addObject(object_type_id, object_name)
        setup = {"kind": "none"}
        if object_type_id == "TechDraw::DrawViewSpreadsheet":
            source = document.addObject("Spreadsheet::Sheet", "ColorSource")
            source.set("A1", "Color probe")
            source.set("B2", "1")
            obj.Source = source
            setup = {"kind": "spreadsheet-source", "objectName": source.Name, "objectTypeId": source.TypeId}
        default_value = color_value(obj, property_name)
        phases = {"default": property_snapshot(document, obj, property_name)}
        requested = {}
        for phase, value in ASSIGNMENTS:
            requested[phase] = list(value) if isinstance(value, tuple) else value
            setattr(obj, property_name, value)
            phases[phase] = property_snapshot(document, obj, property_name)
        setattr(obj, property_name, tuple(default_value))
        phases["restored"] = property_snapshot(document, obj, property_name)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": property_name,
            "mode": "direct-native-property-setter",
            "propertyAssignmentsAccepted": True,
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "setup": setup,
            "defaultValue": default_value,
            "requested": requested,
            "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-color-success",
    "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
    "gitCommit": FREECAD_COMMIT,
    "propertyType": "App::PropertyColor",
    "caseCount": len(cases),
    "cases": cases,
}
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_COLOR_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_COLOR_SUCCESS_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))
