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_FAILURE_OUTPUT", "")


def object_set(document):
    return [{"name": obj.Name, "typeId": obj.TypeId} for obj in document.Objects]


def sha256_file(path):
    if not path or not os.path.isfile(path):
        return None
    with open(path, "rb") as handle:
        return hashlib.sha256(handle.read()).hexdigest()


def snapshot(document, obj):
    path = str(obj.File)
    path_exists = os.path.exists(path) if path else False
    is_file = os.path.isfile(path) if path else False
    is_directory = os.path.isdir(path) if path else False
    mode = stat.S_IMODE(os.stat(path).st_mode) if path_exists else None
    return {
        "value": path,
        "baseName": os.path.basename(path) if path else "",
        "exists": is_file,
        "pathExists": path_exists,
        "isFile": is_file,
        "isDirectory": is_directory,
        "bytes": os.path.getsize(path) if is_file else 0,
        "sha256": sha256_file(path),
        "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("File"),
        "propertyStatus": [str(item) for item in obj.getPropertyStatus("File")],
        "editorMode": [str(item) for item in obj.getEditorMode("File")],
        "objectState": [str(item) for item in obj.State],
        "statusString": str(obj.getStatusString()),
        "objectSet": object_set(document),
    }


def exception_snapshot(callback):
    try:
        callback()
    except Exception as error:
        return {"type": type(error).__name__, "message": str(error)}
    return None


def active_transaction_snapshot():
    active = App.getActiveTransaction()
    if not active:
        return {"name": "", "id": 0}
    return {"name": str(active[0]), "id": int(active[1])}


def run():
    source_dir = tempfile.mkdtemp(prefix="freecad-property-fileincluded-failure-")
    document = App.newDocument("PropertyFileIncludedFailure")
    try:
        source = os.path.join(source_dir, "source.bin")
        replacement = os.path.join(source_dir, "replacement.bin")
        with open(source, "wb") as handle:
            handle.write(b"stable-fileincluded-source\x00\xff\n")
        with open(replacement, "wb") as handle:
            handle.write(b"replacement-fileincluded-source\x00\x80\n")
        source_directory = os.path.join(source_dir, "directory")
        os.mkdir(source_directory)

        obj = document.addObject("App::DocumentObjectFileIncluded", "FileProbe")
        obj.File = (source, "stable.bin")
        document.recompute()
        document.UndoMode = 1
        initial = snapshot(document, obj)
        initial_objects = object_set(document)
        failures = []
        cases = [
            ("missing-path", "/definitely/missing/property-fileincluded.bin"),
            ("wrong-type", 12345),
            ("tuple-wrong-arity", (source,)),
            ("tuple-wrong-name-type", (source, 123)),
            ("dictionary-wrong-filename-type", {"filename": 123}),
        ]
        for case_id, requested in cases:
            before = snapshot(document, obj)
            before_objects = object_set(document)
            assignment_exception = exception_snapshot(lambda value=requested: setattr(obj, "File", value))
            after = snapshot(document, obj)
            failures.append({
                "id": case_id,
                "requested": repr(requested),
                "assignmentException": assignment_exception,
                "before": before,
                "after": after,
                "valuePreserved": before["value"] == after["value"] and before["sha256"] == after["sha256"],
                "objectsPreserved": before_objects == after["objectSet"],
                "objectSetBefore": before_objects,
                "objectSetAfter": after["objectSet"],
            })

        directory_before = snapshot(document, obj)
        directory_exception = exception_snapshot(lambda: setattr(obj, "File", source_directory))
        directory_after = snapshot(document, obj)
        obj.File = (source, "restored-after-directory.bin")
        document.recompute()
        directory_recovery = snapshot(document, obj)
        accepted_risks = [{
            "id": "directory-path",
            "requested": repr(source_directory),
            "assignmentException": directory_exception,
            "before": directory_before,
            "after": directory_after,
            "oldFileRemoved": directory_before["isFile"] and not directory_after["isFile"],
            "directoryAccepted": directory_after["pathExists"] and directory_after["isDirectory"],
            "recovery": directory_recovery,
            "objectsPreserved": directory_before["objectSet"] == directory_after["objectSet"] == directory_recovery["objectSet"],
        }]

        same_before = snapshot(document, obj)
        same_exception = exception_snapshot(lambda: setattr(obj, "File", str(obj.File)))
        same_after = snapshot(document, obj)
        failures.append({
            "id": "same-current-transient",
            "requested": repr(same_before["value"]),
            "assignmentException": same_exception,
            "before": same_before,
            "after": same_after,
            "valuePreserved": same_before["value"] == same_after["value"] and same_before["sha256"] == same_after["sha256"],
            "objectsPreserved": same_before["objectSet"] == same_after["objectSet"],
            "objectSetBefore": same_before["objectSet"],
            "objectSetAfter": same_after["objectSet"],
        })

        filter_before = snapshot(document, obj)
        filter_exception = exception_snapshot(lambda: setattr(obj, "File", {"filter": "Binary (*.bin)"}))
        filter_after = snapshot(document, obj)
        filter_only = {"before": filter_before, "after": filter_after, "exception": filter_exception, "valuePreserved": filter_before["value"] == filter_after["value"] and filter_before["sha256"] == filter_after["sha256"], "objectsPreserved": filter_before["objectSet"] == filter_after["objectSet"]}

        editor_before = snapshot(document, obj)
        obj.setEditorMode("File", ["ReadOnly"])
        editor_mode = [str(item) for item in obj.getEditorMode("File")]
        editor_exception = exception_snapshot(lambda: setattr(obj, "File", (replacement, "editor-write.bin")))
        editor_after = snapshot(document, obj)
        editor_read_only = {"before": editor_before, "editorMode": editor_mode, "exception": editor_exception, "after": editor_after, "pythonBypassesEditorReadOnly": editor_exception is None}
        obj.setEditorMode("File", 0)

        obj.setPropertyStatus("File", "Immutable")
        immutable_status = [str(item) for item in obj.getPropertyStatus("File")]
        immutable_before = snapshot(document, obj)
        immutable_exception = exception_snapshot(lambda: setattr(obj, "File", (replacement, "immutable-write.bin")))
        immutable_after = snapshot(document, obj)
        obj.setPropertyStatus("File", "-Immutable")
        status_restored = [str(item) for item in obj.getPropertyStatus("File")]

        document.recompute()
        document.openTransaction("property-fileincluded-cancel")
        transaction_before = snapshot(document, obj)
        transaction_objects_before = object_set(document)
        setattr(obj, "File", (source, "transaction-write.bin"))
        transaction_edited = snapshot(document, obj)
        edited_path = transaction_edited["value"]
        pending_after_edit = bool(document.HasPendingTransaction)
        active_after_edit = active_transaction_snapshot()
        document.abortTransaction()
        transaction_after_abort = snapshot(document, obj)
        pending_after_abort = bool(document.HasPendingTransaction)
        active_after_abort = active_transaction_snapshot()
        return {
            "schemaVersion": 1,
            "status": "pass",
            "baselineId": "freecad-1.1.1-property-fileincluded-failure",
            "freecadVersion": ".".join(str(value) for value in App.Version()[:3]),
            "gitCommit": FREECAD_COMMIT,
            "propertyType": "App::PropertyFileIncluded",
            "object": {"name": obj.Name, "typeId": obj.TypeId},
            "property": {"name": "File", "typeId": obj.getTypeIdOfProperty("File")},
            "initial": initial,
            "failures": failures,
            "acceptedRisks": accepted_risks,
            "filterOnly": filter_only,
            "editorReadOnly": editor_read_only,
            "immutable": {"status": immutable_status, "before": immutable_before, "exception": immutable_exception, "after": immutable_after, "restoredStatus": status_restored},
            "transaction": {"before": transaction_before, "edited": transaction_edited, "afterAbort": transaction_after_abort, "editedPath": edited_path, "editedPathExistsAfterAbort": os.path.exists(edited_path), "pendingAfterEdit": pending_after_edit, "pendingAfterAbort": pending_after_abort, "activeAfterEdit": active_after_edit, "activeAfterAbort": active_after_abort, "objectsBefore": transaction_objects_before, "objectsAfter": object_set(document), "undoMode": int(document.UndoMode), "restored": transaction_before["value"] == transaction_after_abort["value"] and transaction_before["sha256"] == transaction_after_abort["sha256"]},
            "cancellationBoundary": {"supported": False, "classification": "synchronous-property-setter", "reason": "no-native-cancel-hook", "replacement": "abort-active-document-transaction"},
            "documentIntegrity": {"initialObjects": initial_objects, "finalObjects": object_set(document), "objectsPreserved": initial_objects == object_set(document), "objectCount": len(document.Objects)},
        }
    finally:
        App.closeDocument(document.Name)
        shutil.rmtree(source_dir, ignore_errors=True)


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