import base64
import hashlib
import json
import os
import shutil
import stat
import tempfile

import FreeCAD as App


FREECAD_COMMIT = "0108fd4b4850cc46e625b60e53cea7a7bbe69f8d"
OUTPUT_PATH = os.environ.get("FREECAD_PROPERTY_FILEINCLUDED_MUTATION_OUTPUT", "")
HOSTS = [
    ("App::DocumentObjectFileIncluded", "File"),
    ("App::VRMLObject", "VrmlFile"),
    ("Image::ImagePlane", "ImageFile"),
    ("Robot::RobotObject", "RobotKinematicFile"),
    ("Robot::RobotObject", "RobotVrmlFile"),
    ("Sketcher::SketchObjectSF", "SketchFlatFile"),
    ("TechDraw::DrawComplexSection", "PatIncluded"),
    ("TechDraw::DrawComplexSection", "SvgIncluded"),
    ("TechDraw::DrawComplexSectionPython", "PatIncluded"),
    ("TechDraw::DrawComplexSectionPython", "SvgIncluded"),
    ("TechDraw::DrawGeomHatch", "PatIncluded"),
    ("TechDraw::DrawHatch", "SvgIncluded"),
    ("TechDraw::DrawSVGTemplate", "PageResult"),
    ("TechDraw::DrawTileWeld", "SymbolIncluded"),
    ("TechDraw::DrawTileWeldPython", "SymbolIncluded"),
    ("TechDraw::DrawViewImage", "ImageIncluded"),
    ("TechDraw::DrawViewSection", "PatIncluded"),
    ("TechDraw::DrawViewSection", "SvgIncluded"),
    ("TechDraw::DrawViewSectionPython", "PatIncluded"),
    ("TechDraw::DrawViewSectionPython", "SvgIncluded"),
]


def sha256_file(path):
    with open(path, "rb") as handle:
        return hashlib.sha256(handle.read()).hexdigest()


def write_asset(directory, name, data):
    path = os.path.join(directory, name)
    with open(path, "wb") as handle:
        handle.write(data)
    return path


def create_assets(directory):
    png_a = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")
    png_b = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=") + b"mutation"
    csv_a = b"a,alpha,d,theta,rotDir,maxAngle,minAngle,velocity\n500,-90,1045,0,-1,185,-185,156\n1300,0,0,0,1,35,-155,156\n55,90,0,-90,1,154,-130,156\n0,-90,-1025,0,1,350,-350,330\n0,90,0,0,1,130,-130,330\n0,180,-300,0,1,350,-350,615\n"
    csv_b = b"a,alpha,d,theta,rotDir,maxAngle,minAngle,velocity\n501,-90,1045,0,-1,185,-185,156\n1300,0,0,0,1,35,-155,156\n55,90,0,-90,1,154,-130,156\n0,-90,-1025,0,1,350,-350,330\n0,90,0,0,1,130,-130,330\n0,180,-300,0,1,350,-350,615\n"
    return {
        "binA": write_asset(directory, "before.bin", b"before-fileincluded\x00A\xff\n"),
        "binB": write_asset(directory, "edited.bin", b"edited-fileincluded\x00B\x80\n"),
        "svgA": write_asset(directory, "before.svg", b'<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"><path d="M0 0L4 3"/></svg>\n'),
        "svgB": write_asset(directory, "edited.svg", b'<svg xmlns="http://www.w3.org/2000/svg" width="5" height="4"><path d="M0 4L5 0"/></svg>\n'),
        "patA": write_asset(directory, "before.pat", b"*BEFORE,PropertyFileIncluded\n0, 0,0, 0,2\n"),
        "patB": write_asset(directory, "edited.pat", b"*EDITED,PropertyFileIncluded\n0, 0,0, 0,3\n"),
        "pngA": write_asset(directory, "before.png", png_a),
        "pngB": write_asset(directory, "edited.png", png_b),
        "wrlA": write_asset(directory, "before.wrl", b"#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 } }\n"),
        "wrlB": write_asset(directory, "edited.wrl", b"#VRML V2.0 utf8\nShape { geometry Box { size 2 1 1 } }\n"),
        "csvA": write_asset(directory, "before.csv", csv_a),
        "csvB": write_asset(directory, "edited.csv", csv_b),
        "skfA": write_asset(directory, "before.skf", b"# SketchFlat before fixture\n"),
        "skfB": write_asset(directory, "edited.skf", b"# SketchFlat edited fixture\n"),
    }


def asset_for(property_name, assets, phase):
    suffix = "A" if phase == "before" or phase == "restored" else "B"
    if property_name == "PatIncluded": return assets[f"pat{suffix}"], "pat"
    if property_name in ("SvgIncluded", "PageResult", "SymbolIncluded"): return assets[f"svg{suffix}"], "svg"
    if property_name in ("ImageFile", "ImageIncluded"): return assets[f"png{suffix}"], "png"
    if property_name in ("VrmlFile", "RobotVrmlFile"): return assets[f"wrl{suffix}"], "wrl"
    if property_name == "RobotKinematicFile": return assets[f"csv{suffix}"], "csv"
    if property_name == "SketchFlatFile": return assets[f"skf{suffix}"], "skf"
    return assets[f"bin{suffix}"], "bin"


def shape_snapshot(obj):
    if "Shape" not in obj.PropertiesList:
        return {"applicable": False, "reason": "host-has-no-shape-property"}
    shape = obj.Shape
    return {"applicable": True, "isNull": shape is None or shape.isNull(), "solids": len(shape.Solids), "faces": len(shape.Faces), "edges": len(shape.Edges), "vertices": len(shape.Vertexes)}


def snapshot(document, obj, property_name):
    path = str(getattr(obj, property_name))
    is_file = os.path.isfile(path) if path else False
    mode = stat.S_IMODE(os.stat(path).st_mode) if is_file else None
    return {
        "value": path,
        "baseName": os.path.basename(path) if path else "",
        "exists": is_file,
        "bytes": os.path.getsize(path) if is_file else 0,
        "sha256": sha256_file(path) if is_file else None,
        "writeBits": mode & 0o222 if mode is not None else None,
        "underTransientDir": bool(path) and os.path.commonpath([os.path.abspath(path), os.path.abspath(document.TransientDir)]) == os.path.abspath(document.TransientDir),
        "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(index, object_type_id, property_name, assets):
    document = App.newDocument("PropertyFileIncludedMutation%02d" % index)
    try:
        obj = document.addObject(object_type_id, "MutationProbe")
        archive_name = "mutation-%02d.%s" % (index, "pat" if property_name == "PatIncluded" else "svg" if property_name in ("SvgIncluded", "PageResult", "SymbolIncluded") else "png" if property_name in ("ImageFile", "ImageIncluded") else "wrl" if property_name in ("VrmlFile", "RobotVrmlFile") else "csv" if property_name == "RobotKinematicFile" else "skf" if property_name == "SketchFlatFile" else "bin")
        before_source, _ = asset_for(property_name, assets, "before")
        edited_source, _ = asset_for(property_name, assets, "edited")
        setattr(obj, property_name, (before_source, archive_name))
        document.recompute()
        before = snapshot(document, obj, property_name)
        setattr(obj, property_name, (edited_source, archive_name))
        edited = snapshot(document, obj, property_name)
        edited_recompute = bool(document.recompute())
        edited_after_recompute = snapshot(document, obj, property_name)
        setattr(obj, property_name, (before_source, archive_name))
        restored = snapshot(document, obj, property_name)
        restored_recompute = bool(document.recompute())
        restored_after_recompute = snapshot(document, obj, property_name)
        return {
            "objectTypeId": object_type_id,
            "propertyName": property_name,
            "archiveName": archive_name,
            "beforeSource": {"path": before_source, "bytes": os.path.getsize(before_source), "sha256": sha256_file(before_source)},
            "editedSource": {"path": edited_source, "bytes": os.path.getsize(edited_source), "sha256": sha256_file(edited_source)},
            "before": before,
            "edited": edited,
            "editedRecompute": {"result": edited_recompute, "snapshot": edited_after_recompute},
            "restored": restored,
            "restoredRecompute": {"result": restored_recompute, "snapshot": restored_after_recompute},
            "pathStable": before["value"] == edited["value"] == restored["value"],
            "objectSetStable": before["objectSet"] == edited["objectSet"] == restored["objectSet"] == restored_after_recompute["objectSet"],
        }
    finally:
        App.closeDocument(document.Name)


def run():
    directory = tempfile.mkdtemp(prefix="freecad-property-fileincluded-mutation-")
    try:
        assets = create_assets(directory)
        cases = [run_case(index, *host, assets) for index, host in enumerate(HOSTS)]
        return {"schemaVersion": 1, "status": "pass", "baselineId": "freecad-1.1.1-property-fileincluded-mutation", "freecadVersion": ".".join(str(value) for value in App.Version()[:3]), "gitCommit": FREECAD_COMMIT, "propertyType": "App::PropertyFileIncluded", "caseCount": len(cases), "cases": cases}
    finally:
        shutil.rmtree(directory, ignore_errors=True)


report = run()
if not OUTPUT_PATH:
    raise RuntimeError("FREECAD_PROPERTY_FILEINCLUDED_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_FILEINCLUDED_MUTATION_RESULT=" + json.dumps({"status": report["status"], "caseCount": report["caseCount"]}, sort_keys=True))
