import os, sys, json, traceback

def write_result(ok, 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)

    # Ensure FreeCAD can find user-installed Mods (SheetMetal etc.)
    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)

    # Also add SheetMetal folder explicitly (some setups need it)
    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)

    # argv injection
    sys.argv = ["stepanalyser.py", "--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(False, payload)
    print("RUNNER ERROR:", payload["error_type"], payload["error"], flush=True)

finally:
    os._exit(0)
