import json
import os

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_COLOR_MUTATION_OUTPUT", "")
TARGET = (0.125, 0.375, 0.625, 0.875)
HOSTS = [
    ("App::FeatureTest", "FeatureTestColorMutation", "Colour"),
    ("App::FeatureTestException", "FeatureTestExceptionColorMutation", "Colour"),
    ("App::Part", "PartColorMutation", "Color"),
    ("Assembly::AssemblyLink", "AssemblyLinkColorMutation", "Color"),
    ("Assembly::AssemblyObject", "AssemblyObjectColorMutation", "Color"),
    ("TechDraw::DrawViewAnnotation", "AnnotationColorMutation", "TextColor"),
    ("TechDraw::DrawViewDraft", "DraftColorMutation", "Color"),
    ("TechDraw::DrawViewSpreadsheet", "SpreadsheetColorMutation", "TextColor"),
]


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 snapshot(document, obj, property_name):
    return {
        "value": [round(float(channel), 9) for channel in getattr(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()),
        "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", "MutationSource")
            source.set("A1", "Mutation")
            source.set("B2", "1")
            obj.Source = source
            setup = {"kind": "spreadsheet-source", "objectName": source.Name, "objectTypeId": source.TypeId}
        document.recompute()
        before = snapshot(document, obj, property_name)
        original = list(before["value"])
        setattr(obj, property_name, TARGET)
        touched_after_edit = snapshot(document, obj, property_name)
        edit_recompute_result = bool(document.recompute())
        edited = snapshot(document, obj, property_name)
        setattr(obj, property_name, tuple(original))
        touched_after_restore = snapshot(document, obj, property_name)
        restore_recompute_result = bool(document.recompute())
        restored = snapshot(document, obj, property_name)
        return {
            "objectTypeId": object_type_id,
            "objectName": object_name,
            "propertyName": property_name,
            "hostExecution": "intrinsic-test-exception" if object_type_id == "App::FeatureTestException" else "normal",
            "setup": setup,
            "target": list(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-color-mutation",
    "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_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_COLOR_MUTATION_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"], "restored": sum(1 for case in cases if case["restoredExactly"])}, sort_keys=True))
