"""
rst_to_simviewer.py - convert an Ansys .rst result file into a SimViewer package (.zip)
WITHOUT an Ansys installation, using the open-source reader ansys-mapdl-reader (MIT licence).

    pip install ansys-mapdl-reader pyvista numpy

Usage:
    python rst_to_simviewer.py model.rst --units mm-t-s-MPa          -> model_simviewer.zip
    python rst_to_simviewer.py model.rst --units m-kg-s-Pa -o out.zip --name "My bracket"

--units is required: the reader cannot always tell which unit system the model was solved in.
Format: <length>-<mass>-<time>-<stress>, e.g. m-kg-s-Pa (SI), mm-t-s-MPa, mm-kg-ms-GPa, in-lbm-s-psi.

The package is identical in layout to the one written by rst_to_simviewer_dpf.py
(metadata.json + step_001.vtp, step_002.vtp, ...; same array names, same metadata keys).
Not available from this reader: equivalent_elastic_strain (the viewer simply omits it).

Limitations: ansys-mapdl-reader is not a complete solution. Some result files (notably some
written by recent Ansys versions) and some element types are not supported, and values may
differ slightly from Ansys Mechanical. When an Ansys licence is available, use
rst_to_simviewer_dpf.py instead.
"""
import argparse
import json
import os
import re
import subprocess
import sys
import time
import zipfile

import numpy as np
import pyvista as pv
import vtk

PACKAGE_VERSION = 1
CONVERTER = "ansys-mapdl-reader (open source)"

SOLID_CELLS = {
    10: ("Tet4", None),
    24: ("Tet10", {(0, 1): 4, (1, 2): 5, (0, 2): 6, (0, 3): 7, (1, 3): 8, (2, 3): 9}),
    12: ("Hex8", None),
    25: ("Hex20", {(0, 1): 8, (1, 2): 9, (2, 3): 10, (0, 3): 11, (4, 5): 12, (5, 6): 13, (6, 7): 14,
                   (4, 7): 15, (0, 4): 16, (1, 5): 17, (2, 6): 18, (3, 7): 19}),
    13: ("Wedge6", None),
    26: ("Wedge15", {(0, 1): 6, (1, 2): 7, (0, 2): 8, (3, 4): 9, (4, 5): 10, (3, 5): 11,
                     (0, 3): 12, (1, 4): 13, (2, 5): 14}),
    14: ("Pyramid5", None),
    27: ("Pyramid13", {(0, 1): 5, (1, 2): 6, (2, 3): 7, (0, 3): 8, (0, 4): 9, (1, 4): 10,
                       (2, 4): 11, (3, 4): 12}),
}
LINE_CELLS = {3: 2, 21: 3}
# element faces as corner tuples (VTK node order); with the midside map they give each face's node columns
_TET = [(0, 1, 3), (1, 2, 3), (2, 0, 3), (0, 2, 1)]
_HEX = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
_WED = [(0, 1, 2), (3, 5, 4), (0, 3, 4, 1), (1, 4, 5, 2), (2, 5, 3, 0)]
_PYR = [(0, 3, 2, 1), (0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]
FACE_CORNERS = {10: _TET, 24: _TET, 12: _HEX, 25: _HEX, 13: _WED, 26: _WED, 14: _PYR, 27: _PYR}


def face_columns(vt):
    """Node columns (corners + midside nodes) of every face of a solid cell type."""
    mids = SOLID_CELLS[vt][1] or {}
    out = []
    for f in FACE_CORNERS[vt]:
        cols = list(f)
        for j in range(len(f)):
            a, b = f[j], f[(j + 1) % len(f)]
            if (min(a, b), max(a, b)) in mids:
                cols.append(mids[(min(a, b), max(a, b))])
        out.append(cols)
    return out


def first_three_nodes(surf):
    """(n_polys, 3) local point indices: the first three nodes of every surface polygon."""
    faces = np.asarray(surf.faces)
    out, i = [], 0
    while i < len(faces):
        out.append(faces[i + 1:i + 4])
        i += faces[i] + 1
    return np.asarray(out, dtype=np.int64).reshape(-1, 3)


def element_face_index(tri_nodes, gcell, celltypes, conn, offs):
    """Index of the element face each surface polygon lies on (the viewer draws element edges
    where neighbouring polygons belong to different element faces).
    tri_nodes: (n,3) global node indices of each polygon; gcell: (n,) global cell index."""
    out = np.full(len(gcell), -1, dtype=np.int32)
    for vt in np.unique(celltypes[gcell]):
        sel = np.where(celltypes[gcell] == vt)[0]
        npe = offs[gcell[sel[0]] + 1] - offs[gcell[sel[0]]]
        cc = conn[offs[gcell[sel]][:, None] + np.arange(npe)[None, :]]
        t = tri_nodes[sel]
        for j, cols in enumerate(face_columns(int(vt))):
            fn = cc[:, cols]
            ok = (fn[:, None, :] == t[:, :, None]).any(axis=2).all(axis=1)
            upd = sel[ok & (out[sel] == -1)]
            out[upd] = j
    return out


# MAPDL analysis type code (result header "kan")
ANALYSIS_NAMES = {0: "Static Structural", 1: "Eigenvalue Buckling", 2: "Modal", 3: "Harmonic Response",
                  4: "Transient Structural", 7: "Substructure", 8: "Spectrum"}
# unit system code stored in the result header -> equivalent --units string (only the unambiguous ones)
HEADER_UNITS = {"SI": "m-kg-s-Pa", "MKS": "m-kg-s-Pa", "MPA": "mm-t-s-MPa"}
KNOWN = {"length": {"m", "cm", "mm", "um", "in", "ft"},
         "mass": {"kg", "g", "t", "lbm", "slug"},
         "time": {"s", "ms", "us"},
         "stress": {"Pa", "kPa", "MPa", "GPa", "psi", "ksi", "psf", "dyne/cm^2"}}


def log(msg):
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def parse_units(s):
    parts = s.split("-")
    if len(parts) != 4:
        raise ValueError("expected <length>-<mass>-<time>-<stress>, e.g. mm-t-s-MPa")
    u = dict(zip(("length", "mass", "time", "stress"), parts))
    for k, v in u.items():
        if v not in KNOWN[k]:
            raise ValueError(f"unknown {k} unit '{v}' (known: {', '.join(sorted(KNOWN[k]))})")
    return u


# ----------------------------------------------------------------------------- helpers (same as the DPF script)
def parse_ds_dat(path):
    """Body names per material id, rigid body names and beam connection names from ds.dat."""
    bodies, beams, rigid = {}, [], []
    if not os.path.exists(path):
        return bodies, beams, rigid
    with open(path, encoding="latin-1", errors="replace") as f:
        lines = f.readlines()
    for i, ln in enumerate(lines):
        m = re.search(r"Elements for Body\s+\d+\s+'(.*)'", ln)
        if m:
            name = m.group(1)
            for nxt in lines[i + 1:i + 12]:
                if "Rigid Body" in nxt:
                    rigid.append(name)
                    break
                mm = re.match(r"\s*MAT,\s*(\d+)", nxt, re.I)
                if mm:
                    bodies[int(mm.group(1))] = name
                    break
        m = re.search(r'Create Beam Connection\s+"(.*)"', ln)
        if m:
            beams.append(m.group(1))
    return bodies, beams, rigid


def parse_ds_materials(path):
    """Material names from the 'Model Summary' of ds.dat (lines '! <body>, <material>, matid, <id>'):
    {material id: material name} and {body name: material name}."""
    by_id, by_body = {}, {}
    if not os.path.exists(path):
        return by_id, by_body
    with open(path, encoding="latin-1", errors="replace") as f:
        for ln in f:
            if not ln.startswith("!") or "matid" not in ln:
                continue
            p = [s.strip() for s in ln[1:].rsplit(",", 3)]
            if len(p) == 4 and p[2].lower() == "matid" and p[3].isdigit():
                by_id.setdefault(int(p[3]), p[1])
                by_body[p[0]] = p[1]
    return by_id, by_body


MATML_SKIP = {"Color", "Material Unique Id"}   # not engineering data


def parse_matml(path):
    """Material properties from Mechanical's Engineering Data export (MatML.xml next to the .rst):
    {material name: {"description", "properties": [{"name", "parameters": [{"name", "unit", "values",
    "independent"}]}]}}. Values are in the units given (SI as written by Mechanical). An independent
    parameter (e.g. Temperature) with only Mechanical's placeholder value (~1e-30) is dropped: the
    property is then not temperature dependent."""
    import xml.etree.ElementTree as ET
    if not os.path.exists(path):
        return {}
    try:
        root = ET.parse(path).getroot()
    except ET.ParseError as e:
        log(f"MatML.xml could not be read ({e}) - no material properties")
        return {}
    par_name, par_unit = {}, {}
    for pd in root.iter("ParameterDetails"):
        pid = pd.get("id")
        par_name[pid] = (pd.findtext("Name") or pid).strip()
        units = pd.find("Units")
        parts = []
        if units is not None:
            for u in units.findall("Unit"):
                n, pw = (u.findtext("Name") or "").strip(), (u.get("power") or "1").strip()
                parts.append(n if pw == "1" else f"{n}^{pw}")
        par_unit[pid] = " ".join(parts)
    prop_name = {pr.get("id"): (pr.findtext("Name") or pr.get("id")).strip() for pr in root.iter("PropertyDetails")}
    out = {}
    for m in root.iter("Material"):
        bd = m.find("BulkDetails")
        if bd is None or not (bd.findtext("Name") or "").strip():
            continue
        props = []
        for prd in bd.findall("PropertyData"):
            pname = prop_name.get(prd.get("property"), prd.get("property"))
            if pname in MATML_SKIP:
                continue
            params = []
            for pv in prd.findall("ParameterValue"):
                if pv.get("format") != "float":
                    continue
                try:
                    vals = [float(x) for x in (pv.findtext("Data") or "").split(",") if x.strip()]
                except ValueError:
                    continue
                vtype = next((q.text or "" for q in pv.findall("Qualifier") if q.get("name") == "Variable Type"), "")
                indep = vtype.strip().startswith("Independent")
                if not vals or (indep and all(abs(v) < 1e-20 for v in vals)):
                    continue
                pid = pv.get("parameter")
                params.append({"name": par_name.get(pid, pid), "unit": par_unit.get(pid, ""), "values": vals,
                               "independent": indep})
            if any(not p["independent"] for p in params):
                props.append({"name": pname, "parameters": params})
        out[bd.findtext("Name").strip()] = {"description": (bd.findtext("Description") or "").strip(), "properties": props}
    return out


def material_list(parts, matml):
    """Materials used by the parts, in part order, with their properties from MatML.xml (if any)."""
    out = {}
    for p in parts:
        name = p.get("material")
        if not name:
            continue
        m = out.setdefault(name, {"name": name, "used_by": [], **matml.get(name, {"description": "", "properties": []})})
        m["used_by"].append(p["name"])
    return list(out.values())


def principal_and_vm(s):
    """s: (n, 6) stress tensor XX YY ZZ XY YZ XZ -> (s1, s2, s3, von Mises)."""
    t = np.empty((len(s), 3, 3))
    t[:, 0, 0], t[:, 1, 1], t[:, 2, 2] = s[:, 0], s[:, 1], s[:, 2]
    t[:, 0, 1] = t[:, 1, 0] = s[:, 3]
    t[:, 1, 2] = t[:, 2, 1] = s[:, 4]
    t[:, 0, 2] = t[:, 2, 0] = s[:, 5]
    ev = np.linalg.eigvalsh(np.nan_to_num(t))
    s1, s2, s3 = ev[:, 2], ev[:, 1], ev[:, 0]
    vm = np.sqrt(0.5 * ((s1 - s2) ** 2 + (s2 - s3) ** 2 + (s3 - s1) ** 2))
    bad = np.isnan(s).any(axis=1)
    s1[bad] = vm[bad] = np.nan
    return s1, s2, s3, vm


def fill_midside(arr, blocks):
    """Midside nodes without a result value get the mean of their two corner nodes."""
    for vt, cc in blocks:
        mids = SOLID_CELLS[vt][1]
        if not mids:
            continue
        for (a, b), m in mids.items():
            mid = cc[:, m]
            miss = np.isnan(arr[mid, 0])
            if miss.any():
                arr[mid[miss]] = 0.5 * (arr[cc[miss, a]] + arr[cc[miss, b]])
    return arr


def stats_of(values, nodes, node_nums, coords, disp):
    v = values[nodes]
    if not np.isfinite(v).any():
        return None
    imax, imin = int(np.nanargmax(v)), int(np.nanargmin(v))
    nmax, nmin = nodes[imax], nodes[imin]
    return {"max": float(v[imax]), "max_node": int(node_nums[nmax]), "max_xyz": coords[nmax].tolist(),
            "max_u": disp[nmax].tolist(),
            "min": float(v[imin]), "min_node": int(node_nums[nmin]), "min_xyz": coords[nmin].tolist(),
            "min_u": disp[nmin].tolist()}


def merge_stats(a, b):
    if a is None:
        return b
    if b is None:
        return a
    out = dict(a)
    if b["max"] > a["max"]:
        out.update({k: b[k] for k in ("max", "max_node", "max_xyz", "max_u")})
    if b["min"] < a["min"]:
        out.update({k: b[k] for k in ("min", "min_node", "min_xyz", "min_u")})
    return out


def vtp_bytes(polydata):
    """Serialise PolyData as binary, zlib-compressed VTK XML (readable by vtk.js)."""
    w = vtk.vtkXMLPolyDataWriter()
    w.SetInputData(polydata)
    w.SetDataModeToBinary()
    w.SetCompressorTypeToZLib()
    w.SetHeaderTypeToUInt32()
    w.WriteToOutputStringOn()
    w.Write()
    return w.GetOutputString().encode("latin-1") if isinstance(w.GetOutputString(), str) else bytes(w.GetOutputString())


def model_name_for(rst, title):
    folder = os.path.basename(os.path.dirname(os.path.dirname(os.path.abspath(rst))))
    if folder.endswith("_Mech_Files"):
        return folder[: -len("_Mech_Files")]
    t = (title or "").strip(" -")
    return t or os.path.splitext(os.path.basename(rst))[0]


# ----------------------------------------------------------------------------- main
def convert(rst, out_zip, units_arg, temp_unit, name=None):
    from ansys.mapdl import reader as pymapdl_reader

    t0 = time.time()
    U_ = parse_units(units_arg)
    log(f"Opening {rst}")
    r = pymapdl_reader.read_binary(rst)
    hdr = r._resultheader
    hdr_units = str(hdr.get("units", ""))
    if hdr_units in HEADER_UNITS and HEADER_UNITS[hdr_units] != units_arg:
        log(f"WARNING: the result file says unit system '{hdr_units}' ({HEADER_UNITS[hdr_units]}), "
            f"but --units {units_arg} was given. Using --units.")

    n_sets = int(r.nsets)
    times = np.asarray(r.time_values, dtype=float)
    ls_table = np.asarray(hdr["ls_table"])
    kan = int(hdr.get("kan", -1))

    grid = r.quadgrid  # keeps midside nodes
    node_nums = np.asarray(grid.point_data["ansys_node_num"])
    coords = np.asarray(grid.points, dtype=float)
    mats = np.asarray(grid.cell_data["ansys_material_type"])
    elem_nums = np.asarray(grid.cell_data["ansys_elem_num"])
    celltypes = np.asarray(grid.celltypes)
    conn = np.asarray(grid.cell_connectivity)
    offs = np.asarray(grid.cell_offsets if hasattr(grid, "cell_offsets") else grid.offset)
    grid.point_data["gidx"] = np.arange(grid.n_points, dtype=np.int64)
    grid.cell_data["gcell"] = np.arange(grid.n_cells, dtype=np.int64)
    order = np.argsort(node_nums)
    sorted_nums = node_nums[order]

    def node_index(nums):
        pos = np.clip(np.searchsorted(sorted_nums, nums), 0, len(sorted_nums) - 1)
        ok = sorted_nums[pos] == nums
        return order[pos], ok

    def scatter(nums, data, ncomp):
        out = np.full((len(node_nums), ncomp), np.nan)
        idx, ok = node_index(np.asarray(nums))
        out[idx[ok]] = np.asarray(data, dtype=float).reshape(len(nums), ncomp)[ok]
        return out

    ds_dat = os.path.join(os.path.dirname(os.path.abspath(rst)), "ds.dat")
    body_names, beam_names, rigid_names = parse_ds_dat(ds_dat)
    mat_names, mat_by_body = parse_ds_materials(ds_dat)

    # ---------------- displacement (UX, UY, UZ columns)
    log("Reading displacement")
    U = []
    for k in range(n_sets):
        dof = list(r.result_dof(k))
        nn, d = r.nodal_displacement(k)
        cols = [dof.index(c) if c in dof else None for c in ("UX", "UY", "UZ")]
        u = np.column_stack([d[:, c] if c is not None else np.zeros(len(nn)) for c in cols])
        U.append(scatter(nn, u, 3))

    # ---------------- element nodal stress, averaged per body (material id) below
    log("Reading element stresses")
    elem_stress = []
    for k in range(n_sets):
        enum, es, enode = r.element_stress(k)
        elem_stress.append({int(e): (np.asarray(s, dtype=float), np.asarray(n)) for e, s, n in zip(enum, es, enode)})

    temps = []
    for k in range(n_sets):
        try:
            nn, t = r.nodal_temperature(k)
            temps.append(scatter(nn, t, 1)[:, 0])
        except Exception:
            temps = []
            break
    has_temp = bool(temps) and np.nanmax([np.nanmax(t) for t in temps]) > np.nanmin([np.nanmin(t) for t in temps])

    solid_mask = np.isin(celltypes, list(SOLID_CELLS))
    part_mats = sorted(set(mats[solid_mask].tolist()))
    parts, surfaces, part_values = [], [], []
    for pid, mat in enumerate(part_mats):
        cells = np.where(solid_mask & (mats == mat))[0]
        pname = body_names.get(int(mat), f"Body (material {mat})")
        blocks, type_names = [], []
        for vt in sorted(set(celltypes[cells].tolist())):
            c = cells[celltypes[cells] == vt]
            npe = offs[c[0] + 1] - offs[c[0]]
            blocks.append((vt, conn[offs[c][:, None] + np.arange(npe)[None, :]]))
            type_names.append(SOLID_CELLS[vt][0])
        part_nodes = np.unique(np.concatenate([b[1].ravel() for b in blocks]))

        sub = grid.extract_cells(cells)
        surf = sub.extract_surface(nonlinear_subdivision=1, algorithm="dataset_surface")
        gidx = np.asarray(surf.point_data["gidx"], dtype=np.int64)
        gcell = np.asarray(surf.cell_data["gcell"], dtype=np.int64)
        assert np.allclose(surf.points, coords[gidx]), "surface points do not map to mesh nodes"
        surf = pv.PolyData(coords[gidx], surf.faces)
        surf.cell_data["part_id"] = np.full(surf.n_cells, pid, dtype=np.int32)
        surf.cell_data["ansys_elem_num"] = elem_nums[gcell].astype(np.int32)
        surf.cell_data["elem_face"] = element_face_index(gidx[first_three_nodes(surf)], gcell, celltypes, conn, offs)
        surf.cell_data["elem_type"] = np.array([type_names.index(SOLID_CELLS[int(t)][0]) for t in celltypes[gcell]],
                                               dtype=np.int32)
        surf_elems = elem_nums[gcell].tolist()
        log(f"Part {pid} '{pname}' (mat {mat}): {len(cells)} elements {type_names}, "
            f"{len(part_nodes)} nodes, surface {surf.n_points} points / {surf.n_cells} triangles")

        part_elems = elem_nums[cells].tolist()
        vals = []
        for k in range(n_sets):
            acc = np.zeros((len(node_nums), 6))
            cnt = np.zeros(len(node_nums))
            for e in part_elems:
                item = elem_stress[k].get(int(e))
                if item is None or item[0].ndim != 2 or item[0].shape[1] < 6:
                    continue
                s, n = item
                m = min(len(s), len(n))
                idx, ok = node_index(n[:m])
                good = ok & ~np.isnan(s[:m, :6]).any(axis=1)
                np.add.at(acc, idx[good], s[:m][good, :6])
                np.add.at(cnt, idx[good], 1)
            st = np.full((len(node_nums), 6), np.nan)
            st[cnt > 0] = acc[cnt > 0] / cnt[cnt > 0, None]
            st = fill_midside(st, blocks)
            s1, s2, s3, vm = principal_and_vm(st)
            v = {"von_mises_stress": vm, "max_principal_stress": s1, "mid_principal_stress": s2,
                 "min_principal_stress": s3}
            # element mean / max of the unaveraged von Mises stress, per surface polygon
            emean, emax = {}, {}
            for e in set(surf_elems):
                item = elem_stress[k].get(int(e))
                if item is None or item[0].ndim != 2 or item[0].shape[1] < 6:
                    continue
                vv = principal_and_vm(item[0][:, :6])[3]
                if np.isfinite(vv).any():
                    emean[e], emax[e] = np.nanmean(vv), np.nanmax(vv)
            v["_elem_mean"] = np.array([emean.get(e, np.nan) for e in surf_elems])
            v["_elem_max"] = np.array([emax.get(e, np.nan) for e in surf_elems])
            if has_temp:
                v["temperature"] = temps[k]
            vals.append(v)
        parts.append({"id": pid, "name": pname, "kind": "solid", "material_id": int(mat),
                      "material": mat_names.get(int(mat)), "element_types": type_names, "n_elements": int(len(cells)), "n_nodes": int(len(part_nodes))})
        surfaces.append((surf, gidx, part_nodes))
        part_values.append(vals)

    beam_cells = np.where(np.isin(celltypes, list(LINE_CELLS)))[0]
    beam = None
    if len(beam_cells):
        segs, seg_elem = [], []
        for c in beam_cells:
            n = conn[offs[c]:offs[c] + LINE_CELLS[int(celltypes[c])]]
            n = [n[0], n[2], n[1]] if len(n) == 3 else list(n)
            segs += [(n[i], n[i + 1]) for i in range(len(n) - 1)]
            seg_elem += [elem_nums[c]] * (len(n) - 1)
        segs = np.array(segs)
        bnodes = np.unique(segs.ravel())
        local = {g: i for i, g in enumerate(bnodes)}
        lines = np.hstack([np.full((len(segs), 1), 2), np.vectorize(local.get)(segs)]).ravel()
        bpd = pv.PolyData(coords[bnodes], lines=lines)
        pid = len(parts)
        bpd.cell_data["part_id"] = np.full(bpd.n_cells, pid, dtype=np.int32)
        bpd.cell_data["ansys_elem_num"] = np.asarray(seg_elem, dtype=np.int32)
        bpd.cell_data["elem_face"] = np.zeros(bpd.n_cells, dtype=np.int32)
        bpd.cell_data["elem_type"] = np.zeros(bpd.n_cells, dtype=np.int32)
        parts.append({"id": pid, "name": "Beam connections" + (f" ({len(beam_names)})" if beam_names else ""),
                      "kind": "beam", "members": beam_names, "element_types": ["Beam"],
                      "n_elements": int(len(beam_cells)), "n_nodes": int(len(bnodes))})
        beam = (bpd, bnodes)
    for nm in rigid_names:
        parts.append({"id": len(parts), "name": nm, "kind": "rigid", "material": mat_by_body.get(nm),
                      "element_types": [], "n_elements": 0, "n_nodes": 0})

    start = 0
    for p, (surf, _, _) in zip(parts, surfaces):
        p["point_start"], p["point_count"] = start, int(surf.n_points)
        start += surf.n_points
    if beam:
        bp = next(p for p in parts if p["kind"] == "beam")
        bp["point_start"], bp["point_count"] = start, int(beam[0].n_points)

    length_unit, stress_unit = U_["length"], U_["stress"]
    time_unit = "Hz" if kan in (2, 3) else U_["time"]
    fields = [
        {"name": "displacement", "label": "Directional Deformation", "unit": length_unit, "components": 3},
        {"name": "displacement_magnitude", "label": "Total Deformation", "unit": length_unit, "components": 1},
        {"name": "von_mises_stress", "label": "Equivalent (von-Mises) Stress", "unit": stress_unit, "components": 1},
        {"name": "max_principal_stress", "label": "Maximum Principal Stress", "unit": stress_unit, "components": 1},
        {"name": "mid_principal_stress", "label": "Middle Principal Stress", "unit": stress_unit, "components": 1},
        {"name": "min_principal_stress", "label": "Minimum Principal Stress", "unit": stress_unit, "components": 1},
    ]
    if has_temp:
        fields.append({"name": "temperature", "label": "Temperature", "unit": temp_unit, "components": 1})
    scalar_names = [f["name"] for f in fields if f["components"] == 1]
    stat_names = scalar_names + ["displacement_x", "displacement_y", "displacement_z"]

    os.makedirs(os.path.dirname(os.path.abspath(out_zip)), exist_ok=True)
    steps = []
    with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
        for k in range(n_sets):
            s = k + 1  # result set numbers are 1-based, the reader's index is 0-based
            u = np.nan_to_num(U[k])
            umag = np.linalg.norm(u, axis=1)
            pieces, step_parts, overall = [], {}, {}
            for p, (surf, gidx, part_nodes), vals in zip(parts, surfaces, part_values):
                v = dict(vals[k])
                v["displacement_magnitude"] = umag
                v["displacement_x"], v["displacement_y"], v["displacement_z"] = u[:, 0], u[:, 1], u[:, 2]
                pd = surf.copy()
                pd.point_data["displacement"] = u[gidx].astype(np.float32)
                for nm in scalar_names:
                    pd.point_data[nm] = v[nm][gidx].astype(np.float32)
                pd.point_data["ansys_node_num"] = node_nums[gidx].astype(np.int32)
                pd.cell_data["von_mises_elem_mean"] = v["_elem_mean"].astype(np.float32)
                pd.cell_data["von_mises_elem_max"] = v["_elem_max"].astype(np.float32)
                pieces.append(pd)
                ps = {nm: stats_of(v[nm], part_nodes, node_nums, coords, u) for nm in stat_names}
                step_parts[str(p["id"])] = ps
                for nm in stat_names:
                    overall[nm] = merge_stats(overall.get(nm), ps[nm])
            if beam:
                bpd, bnodes = beam
                pd = bpd.copy()
                pd.point_data["displacement"] = u[bnodes].astype(np.float32)
                for nm in scalar_names:
                    pd.point_data[nm] = (umag[bnodes] if nm == "displacement_magnitude"
                                         else np.full(len(bnodes), np.nan)).astype(np.float32)
                pd.point_data["ansys_node_num"] = node_nums[bnodes].astype(np.int32)
                pd.cell_data["von_mises_elem_mean"] = np.full(pd.n_cells, np.nan, dtype=np.float32)
                pd.cell_data["von_mises_elem_max"] = np.full(pd.n_cells, np.nan, dtype=np.float32)
                pieces.append(pd)
            app = vtk.vtkAppendPolyData()
            for pd in pieces:
                app.AddInputData(pd)
            app.Update()
            fname = f"step_{s:03d}.vtp"
            zf.writestr(fname, vtp_bytes(app.GetOutput()))
            ls, ss = (int(ls_table[k, 0]), int(ls_table[k, 1])) if k < len(ls_table) else (None, None)
            steps.append({"set": s, "time": float(times[k]), "load_step": ls, "substep": ss, "file": fname,
                          "fields": overall, "parts": step_parts})
            vm, dm = overall["von_mises_stress"], overall["displacement_magnitude"]
            log(f"   set {s}: time {times[k]:g} {time_unit}  max von Mises {vm['max']:.6g} {stress_unit} "
                f"(node {vm['max_node']})  max displacement {dm['max']:.6g} {length_unit} (node {dm['max_node']})")

        import ansys.mapdl.reader as _rdr
        title = str(hdr.get("title", "")).strip()
        meta = {
            "package_version": PACKAGE_VERSION,
            "source_file": os.path.basename(rst),
            "model_name": name or model_name_for(rst, title),
            "title": title,
            "analysis_type": ANALYSIS_NAMES.get(kan, f"Unknown ({kan})"),
            "solver": "MAPDL",
            "solver_version": str(hdr.get("verstring", "")),
            "converter": CONVERTER,
            "converter_version": f"ansys-mapdl-reader {getattr(_rdr, '__version__', '?')}",
            "created": time.strftime("%Y-%m-%dT%H:%M:%S"),
            "unit_system": f"{units_arg} (user supplied; file header: {hdr_units or 'n/a'})",
            "units": {**{f["name"]: f["unit"] for f in fields}, "length": length_unit, "time": time_unit},
            "time_quantity": "Frequency" if kan in (2, 3) else "Time",
            "averaging": "nodal, per body (no averaging across bodies)",
            "n_nodes": int(len(node_nums)),
            "n_elements": int(grid.n_cells),
            "fields": fields,
            "parts": parts,
            "materials": material_list(parts, parse_matml(os.path.join(os.path.dirname(os.path.abspath(rst)), "MatML.xml"))),
            "steps": steps,
        }
        zf.writestr("metadata.json", json.dumps(meta, indent=1))

    vm_all = max(steps, key=lambda st: st["fields"]["von_mises_stress"]["max"])
    dm_all = max(steps, key=lambda st: st["fields"]["displacement_magnitude"]["max"])
    print()
    print(f"SimViewer package: {out_zip} ({os.path.getsize(out_zip) / 1e6:.1f} MB, {time.time() - t0:.0f} s)")
    print(f"  model            : {meta['model_name']}  ({meta['analysis_type']}, {meta['unit_system']})")
    print(f"  steps            : {len(steps)}")
    print(f"  fields           : {', '.join(f['name'] for f in fields)}")
    print(f"  parts            : {', '.join(p['name'] for p in parts)}")
    print(f"  max von Mises    : {vm_all['fields']['von_mises_stress']['max']:.6g} {stress_unit} "
          f"(set {vm_all['set']}, node {vm_all['fields']['von_mises_stress']['max_node']})")
    print(f"  max displacement : {dm_all['fields']['displacement_magnitude']['max']:.6g} {length_unit} "
          f"(set {dm_all['set']}, node {dm_all['fields']['displacement_magnitude']['max_node']})")


def main():
    ap = argparse.ArgumentParser(description="Convert an Ansys .rst file into a SimViewer package (.zip) "
                                             "with the open-source ansys-mapdl-reader (no Ansys needed).")
    ap.add_argument("rst", help="Ansys result file (.rst)")
    ap.add_argument("--units", required=True,
                    help="unit system of the model: <length>-<mass>-<time>-<stress>, e.g. mm-t-s-MPa or m-kg-s-Pa")
    ap.add_argument("--temp-unit", default="degC", help="temperature unit (default degC)")
    ap.add_argument("-o", "--output", help="output .zip (default: <name>_simviewer.zip in the current folder)")
    ap.add_argument("--name", help="model name shown in the viewer")
    ap.add_argument("--_worker", action="store_true", help=argparse.SUPPRESS)
    a = ap.parse_args()
    if not os.path.isfile(a.rst):
        sys.exit(f"File not found: {a.rst}")
    try:
        parse_units(a.units)
    except ValueError as e:
        sys.exit(f"--units: {e}")
    out = a.output or os.path.splitext(os.path.basename(a.rst))[0] + "_simviewer.zip"

    if a._worker:
        convert(a.rst, out, a.units, a.temp_unit, a.name)
        return
    # The reader's compiled parts can crash hard (no Python exception) on files they do not
    # support. Run the conversion in a child process so we can explain what happened.
    started = time.time()
    if getattr(sys, "frozen", False):   # inside the packaged SimViewer Converter: the program runs the worker
        rc = subprocess.call([sys.executable, "--convert", "oss", *sys.argv[1:], "--_worker"],
                             creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
    else:
        rc = subprocess.call([sys.executable, os.path.abspath(__file__), *sys.argv[1:], "--_worker"])
    if rc != 0:
        if os.path.exists(out) and os.path.getmtime(out) >= started - 1:
            try:
                os.remove(out)  # incomplete package
            except OSError:
                pass
        sys.exit(f"\nConversion failed (exit code {rc}). ansys-mapdl-reader could not read this result file "
                 f"(it does not support every file version or element type).\n"
                 f"If you have an Ansys licence, use rst_to_simviewer_dpf.py instead.")


if __name__ == "__main__":
    main()
