import os, sys, json, traceback

def write_result(payload):
    try:
        with open("result.json", "w", encoding="utf-8") as f:
            json.dump(payload, f, indent=2, ensure_ascii=False)
    except Exception:
        pass

try:
    base = os.path.dirname(os.path.abspath(__file__))
    os.chdir(base)

    if not os.path.exists("test.step"):
        raise SystemExit("Uploaded STEP file missing: " + "test.step")

    # Ensure FreeCAD can find user Mods (SheetMetal installed in user profile)
    mod_dir = os.path.expanduser("~/Library/Application Support/FreeCAD/Mod")
    if os.path.isdir(mod_dir) and mod_dir not in sys.path:
        sys.path.append(mod_dir)
    sm_dir = os.path.join(mod_dir, "SheetMetal")
    if os.path.isdir(sm_dir) and sm_dir not in sys.path:
        sys.path.append(sm_dir)

    sys.argv = ["stepanalyser.py", "--input", "test.step", "--material", "stainless"]

    code = open("stepanalyser.py", "r", encoding="utf-8").read()
    exec(compile(code, "stepanalyser.py", "exec"), {"__name__": "__main__"})

except BaseException as e:
    payload = {
        "ok": False,
        "error_type": type(e).__name__,
        "error": str(e),
        "traceback": traceback.format_exc()
    }
    write_result(payload)
    print("RUNNER ERROR:", payload["error_type"], payload["error"], flush=True)

finally:
    os._exit(0)
