"""
rst_to_simviewer_dpf.py - convert an Ansys .rst result file into a SimViewer package (.zip).

Needs a local Ansys installation (PyDPF-Core starts the DPF server that ships with Ansys)
plus:  pip install ansys-dpf-core pyvista numpy

Usage:
    python rst_to_simviewer_dpf.py model.rst                -> model_simviewer.zip
    python rst_to_simviewer_dpf.py model.rst -o out.zip --name "My bracket"

Package layout (package_version 1):
    metadata.json
    step_001.vtp, step_002.vtp, ...   one per result set: outer surface of every body,
                                       binary + zlib-compressed VTK XML PolyData

Point-data arrays on each .vtp:
    displacement (3 comp.), displacement_magnitude, von_mises_stress, max_principal_stress,
    mid_principal_stress, min_principal_stress, equivalent_elastic_strain (if in the file),
    temperature (only if the file has a temperature field that varies), ansys_node_num
Cell-data arrays: part_id, ansys_elem_num, elem_face (face of the element the polygon lies on),
    elem_type (index into the part's element_types), von_mises_elem_mean / von_mises_elem_max
    (unaveraged element-nodal von Mises, mean and max over the element's nodes)

Elements: 3D solids (tet, hex, wedge, pyramid), shells and 2D plane elements (tri, quad), each linear
or quadratic, are drawn as surfaces; beams, links and pipes (linear or quadratic) as lines, deformation
only. Contact, target, pretension, surface-effect, spring, mass and interface elements are not shown;
they are recognised by their Ansys element type number. Shells: von Mises, maximum/middle principal
stress and equivalent strain show the larger of the top and bottom value, minimum principal the smaller.

Section view data (section/...): per body with 3D elements, part_NNN.bin = node coordinates (float32 n*3)
followed by linear sub-tetrahedra (uint32 m*4, part-local node numbers); per result set step_NNN.bin =
for every body in metadata order: displacement (float32 n*3), then each field of section.fields (float32 n).

Named selections (Ansys node / element components, except Mechanical's internal ones starting with "_")
are written to metadata.json with the node / element numbers on the displayed surface (for highlighting)
and, per result set, the max / min of every result over all their nodes.

Parts: bodies are grouped by material id; body names, rigid bodies and beam
connections are taken from Mechanical's ds.dat next to the .rst when it exists.
Nodal results are averaged per body (no averaging across bodies), von Mises and
principal stresses are computed from the averaged nodal stress tensor.
Values are written in the units stored in the .rst; units are read from DPF.
"""
import argparse
import io
import json
import os
import re
import sys
import time
import zipfile

import numpy as np
import pyvista as pv
import vtk
from ansys.dpf import core as dpf
from ansys.dpf.core.vtk_helper import dpf_mesh_to_vtk

PACKAGE_VERSION = 1
CONVERTER = "PyDPF"

# Solid VTK cell types: name and midside-node map {(corner a, corner b): midside node}
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}),
}
# 2D cell types (shells and plane elements): the element itself is the surface
SURFACE_CELLS = {
    5: ("Tri3", None),
    9: ("Quad4", None),
    22: ("Tri6", {(0, 1): 3, (1, 2): 4, (0, 2): 5}),
    23: ("Quad8", {(0, 1): 4, (1, 2): 5, (2, 3): 6, (0, 3): 7}),
}
AREA_CELLS = {**SOLID_CELLS, **SURFACE_CELLS}  # everything drawn as a coloured surface
LINE_CELLS = {3: 2, 21: 3}  # VTK_LINE, VTK_QUADRATIC_EDGE (end, end, mid) -> node count
# 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,
                5: [(0, 1, 2)], 22: [(0, 1, 2)], 9: [(0, 1, 2, 3)], 23: [(0, 1, 2, 3)]}

# Section view: every 3D element is split into linear tetrahedra (VTK node columns), which the browser
# cuts with the section plane. Tet10 uses all 10 nodes (4 corner tets + 4 tets of the inner octahedron);
# the other quadratic types are split on their corner nodes.
_TET_SUB = [(0, 1, 2, 3)]
_TET10_SUB = [(0, 4, 6, 7), (4, 1, 5, 8), (6, 5, 2, 9), (7, 8, 9, 3),
              (4, 9, 5, 8), (4, 9, 8, 7), (4, 9, 7, 6), (4, 9, 6, 5)]
_HEX_SUB = [(0, 1, 2, 6), (0, 2, 3, 6), (0, 3, 7, 6), (0, 7, 4, 6), (0, 4, 5, 6), (0, 5, 1, 6)]
_WED_SUB = [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)]
_PYR_SUB = [(0, 1, 2, 4), (0, 2, 3, 4)]
SUB_TETS = {10: _TET_SUB, 24: _TET10_SUB, 12: _HEX_SUB, 25: _HEX_SUB, 13: _WED_SUB, 26: _WED_SUB,
            14: _PYR_SUB, 27: _PYR_SUB}

# Ansys element type numbers (DPF property field "apdl_element_type") that tell real 2D / line elements
# apart from contact, target, pretension, surface-effect and other helper elements of the same shape.
SHELL_APDL = {28, 41, 43, 57, 63, 91, 93, 99, 131, 132, 143, 150, 157, 163, 181, 208, 209, 281}
PLANE_APDL = {2, 13, 25, 35, 42, 53, 55, 67, 77, 78, 82, 83, 121, 145, 146, 162, 182, 183, 223, 230, 233,
              292, 293}
LINE_APDL = {1, 3, 4, 8, 10, 11, 16, 18, 20, 23, 24, 31, 33, 34, 44, 54, 59, 60, 61, 68, 161, 180, 188, 189,
             288, 289, 290}  # beams, links, pipes, elbows
INTERFACE_APDL = {192, 193, 194, 195, 202, 203, 204, 205}  # gasket / cohesive interface elements (not shown)


def element_roles(celltypes, apdl):
    """'solid', 'shell', 'plane', 'line' or '' (not shown) for every cell.
    Without element type numbers (apdl None): 3D cells are solids, line cells beams, 2D cells are skipped,
    because they cannot be told apart from contact elements."""
    roles = np.full(len(celltypes), "", dtype=object)
    is_solid = np.isin(celltypes, list(SOLID_CELLS))
    is_surf = np.isin(celltypes, list(SURFACE_CELLS))
    is_line = np.isin(celltypes, list(LINE_CELLS))
    if apdl is None:
        roles[is_solid] = "solid"
        roles[is_line] = "line"
        return roles
    roles[is_solid & ~np.isin(apdl, list(INTERFACE_APDL))] = "solid"
    roles[is_surf & np.isin(apdl, list(SHELL_APDL))] = "shell"
    roles[is_surf & np.isin(apdl, list(PLANE_APDL))] = "plane"
    roles[is_line & np.isin(apdl, list(LINE_APDL))] = "line"
    return roles


def type_name(vt, role):
    """Element type shown in the viewer, e.g. 'Tet10', 'Quad8 shell', 'Tri6 plane'."""
    return AREA_CELLS[vt][0] + {"shell": " shell", "plane": " plane"}.get(role, "")


def face_columns(vt):
    """Node columns (corners + midside nodes) of every face of a solid or 2D cell type."""
    mids = AREA_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

ANALYSIS_NAMES = {"static": "Static Structural", "modal": "Modal", "transient": "Transient Structural",
                  "harmonic": "Harmonic Response", "buckling": "Eigenvalue Buckling",
                  "steady": "Steady-State Thermal"}


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


# ----------------------------------------------------------------------------- helpers
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 in DPF order 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 = AREA_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):
    """Max/min of `values` over global node indices `nodes` with node number, XYZ and displacement,
    plus the average over the nodes with a value (avg) and their number (n)."""
    v = values[nodes]
    ok = np.isfinite(v)
    if not ok.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(),
            "avg": float(v[ok].mean()), "n": int(ok.sum())}


def merge_stats(a, b):
    """Combine two stats dicts (e.g. of two parts) into the overall max/min."""
    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")})
    if "n" in a and "n" in b:                      # average over all nodes of both, weighted by node count
        out["n"] = a["n"] + b["n"]
        out["avg"] = (a["avg"] * a["n"] + b["avg"] * b["n"]) / out["n"]
    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):
    """Mechanical project layout <name>_Mech_Files/<System>/file.rst -> <name>; else title or file stem."""
    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, name=None):
    t0 = time.time()
    log(f"Opening {rst}")
    model = dpf.Model(rst)
    ds = model.metadata.data_sources
    ri = model.metadata.result_info
    mesh = model.metadata.meshed_region
    tf = model.metadata.time_freq_support
    times = np.asarray(tf.time_frequencies.data, dtype=float)
    time_unit = tf.time_frequencies.unit or ""
    n_sets = len(times)
    sets = list(range(1, n_sets + 1))  # DPF result sets are 1-based

    # load step / substep of each cumulative set
    lsss, cum = {}, 1
    for ls_id in tf.time_frequencies.scoping.ids:
        for ss in range(len(tf.time_frequencies.get_entity_data_by_id(ls_id))):
            lsss[cum] = (int(ls_id), ss + 1)
            cum += 1

    node_nums = np.asarray(mesh.nodes.scoping.ids)
    elem_ids = np.asarray(mesh.elements.scoping.ids)
    mats = np.asarray(mesh.elements.materials_field.data)
    order = np.argsort(node_nums)
    sorted_nums = node_nums[order]

    def scatter(field, ncomp):
        """DPF field (any node order) -> (n_nodes, ncomp) array in mesh node order, NaN where missing."""
        out = np.full((len(node_nums), ncomp), np.nan)
        ids = np.asarray(field.scoping.ids)
        if len(ids) == 0:
            return out
        pos = np.searchsorted(sorted_nums, ids)
        if np.any(sorted_nums[np.clip(pos, 0, len(sorted_nums) - 1)] != ids):
            raise ValueError("result references an unknown node number")
        out[order[pos]] = np.asarray(field.data).reshape(len(ids), ncomp)
        return out

    log("Building VTK grid from the DPF mesh")
    grid = dpf_mesh_to_vtk(mesh, as_linear=False)  # keep midside nodes
    coords = np.asarray(mesh.nodes.coordinates_field.data, dtype=float)
    assert grid.n_points == len(node_nums) and np.allclose(grid.points, coords), "node order mismatch"
    assert grid.n_cells == len(elem_ids), "cell count mismatch"
    grid.point_data["gidx"] = np.arange(grid.n_points, dtype=np.int64)
    grid.cell_data["gcell"] = np.arange(grid.n_cells, dtype=np.int64)
    celltypes = np.asarray(grid.celltypes)
    conn = np.asarray(grid.cell_connectivity)
    offs = np.asarray(grid.offset)

    # what every element is (solid / shell / plane / line / not shown), from the Ansys element type number
    apdl = None
    if "apdl_element_type" in mesh.available_property_fields:
        pf = mesh.property_field("apdl_element_type")
        pf_ids, pf_data = np.asarray(pf.scoping.ids), np.asarray(pf.data)
        if len(pf_ids) == len(elem_ids) and np.array_equal(pf_ids, elem_ids):
            apdl = pf_data
        else:
            lut = dict(zip(pf_ids.tolist(), pf_data.tolist()))
            apdl = np.array([lut.get(e, -1) for e in elem_ids.tolist()])
    else:
        log("No element type numbers in the file: 2D elements are skipped, line elements shown as beams")
    roles = element_roles(celltypes, apdl)
    hidden = (roles == "") & ~np.isin(celltypes, [1])          # point elements (masses, contact nodes) never shown
    if hidden.any():
        what = {}
        for a in (apdl[hidden] if apdl is not None else celltypes[hidden]):
            what[int(a)] = what.get(int(a), 0) + 1
        log("Not shown (contact, target, pretension and other helper elements): "
            + ", ".join(f"{'type' if apdl is not None else 'VTK cell'} {k} ({n})" for k, n in sorted(what.items())))

    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)

    # ---------------- units (read from DPF, never assumed)
    log("Reading displacement")
    disp_fc = dpf.operators.result.displacement(time_scoping=sets, data_sources=ds).outputs.fields_container()
    U = [scatter(disp_fc.get_field_by_time_id(s), 3) for s in sets]
    length_unit = disp_fc.get_field_by_time_id(sets[0]).unit

    available = {r.name for r in ri.available_results}
    temp_result = "temperature" if "temperature" in available else (
        "structural_temperature" if "structural_temperature" in available else None)

    # ---------------- surface parts (one per material id): solids, shells and 2D plane elements
    area_mask = np.isin(roles, ["solid", "shell", "plane"])
    part_mats = sorted(set(mats[area_mask].tolist()))
    parts, surfaces, part_values, section_parts = [], [], [], []
    stress_unit, temp_unit, strain_unit = None, None, None
    temps_by_part = []
    for pid, mat in enumerate(part_mats):
        cells = np.where(area_mask & (mats == mat))[0]
        pname = body_names.get(mat, f"Body (material {mat})")
        has_shell = bool((roles[cells] == "shell").any())
        blocks, type_names, vt_name = [], [], {}
        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, :]]))
            vt_name[vt] = type_name(vt, roles[c[0]])
            type_names.append(vt_name[vt])
        part_nodes = np.unique(np.concatenate([b[1].ravel() for b in blocks]))

        # volume of the 3D elements for the section view: linear sub-tetrahedra in part-local node numbers
        sub = [cc[:, list(t)] for vt, cc in blocks if vt in SUB_TETS for t in SUB_TETS[vt]]
        if sub:
            sec_tets = np.searchsorted(part_nodes, np.concatenate(sub)).astype(np.uint32)
            section_parts.append({"pid": pid, "nodes": part_nodes, "tets": sec_tets})

        # outer surface of this body (quadratic faces split into linear triangles on existing nodes)
        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)  # element (global cell) of each polygon
        assert np.allclose(surf.points, coords[gidx]), "surface points do not map to mesh nodes"
        surf = pv.PolyData(coords[gidx], surf.faces)  # clean copy without helper arrays
        surf.cell_data["part_id"] = np.full(surf.n_cells, pid, dtype=np.int32)
        # element information per surface polygon (probe details and element edges in the viewer)
        surf.cell_data["ansys_elem_num"] = elem_ids[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(vt_name[int(t)]) for t in celltypes[gcell]],
                                               dtype=np.int32)
        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")

        # results averaged within this body only
        # shells: top and bottom layer read separately, the viewer shows the larger value (Top/Bottom max)
        esc = dpf.Scoping(ids=elem_ids[cells].tolist(), location=dpf.locations.elemental)
        layers = [0, 1] if has_shell else [None]               # DPF shell_layer: 0 top, 1 bottom

        def nodal(op_cls, layer):
            op = op_cls(time_scoping=sets, mesh_scoping=esc, data_sources=ds, requested_location=dpf.locations.nodal)
            if layer is not None:
                op.inputs.shell_layer.connect(layer)
            return op.outputs.fields_container()
        s_fcs = [nodal(dpf.operators.result.stress, ly) for ly in layers]
        stress_unit = s_fcs[0].get_field_by_time_id(sets[0]).unit
        ep_fcs = None
        if "elastic_strain_eqv" in available or "elastic_strain" in available:
            try:
                ep_fcs = [nodal(dpf.operators.result.elastic_strain_eqv, ly) for ly in layers]
                strain_unit = ep_fcs[0].get_field_by_time_id(sets[0]).unit
            except Exception as e:  # not every file has elastic strains
                log(f"   no equivalent elastic strain ({e})")
                ep_fcs = None
        # unaveraged (element nodal) stress of the surface elements -> element mean / max von Mises
        surf_eids = np.unique(elem_ids[gcell])
        esc_s = dpf.Scoping(ids=surf_eids.tolist(), location=dpf.locations.elemental)
        se_fc = dpf.operators.result.stress(time_scoping=sets, mesh_scoping=esc_s, data_sources=ds,
                                            requested_location=dpf.locations.elemental_nodal).outputs.fields_container()
        t_fc = None
        if temp_result:
            op = getattr(dpf.operators.result, temp_result)
            t_fc = op(time_scoping=sets, mesh_scoping=esc, data_sources=ds,
                      requested_location=dpf.locations.nodal).outputs.fields_container()
            temp_unit = t_fc.get_field_by_time_id(sets[0]).unit
        vals = []
        for s in sets:
            res = [principal_and_vm(fill_midside(scatter(fc.get_field_by_time_id(s), 6), blocks)) for fc in s_fcs]
            s1, s2, s3, vm = res[0]
            for r1, r2, r3, rv in res[1:]:                       # shell envelope: larger of top / bottom
                s1, s2, s3, vm = np.fmax(s1, r1), np.fmax(s2, r2), np.fmin(s3, r3), np.fmax(vm, rv)
            v = {"von_mises_stress": vm, "max_principal_stress": s1, "mid_principal_stress": s2,
                 "min_principal_stress": s3}
            if ep_fcs is not None:
                eps = [fill_midside(scatter(fc.get_field_by_time_id(s), 1), blocks)[:, 0] for fc in ep_fcs]
                v["equivalent_elastic_strain"] = eps[0] if len(eps) == 1 else np.fmax(eps[0], eps[1])
            # element mean / max of the unaveraged von Mises stress, per surface polygon
            sef = se_fc.get_field_by_time_id(s)
            se_ids, sed = np.asarray(sef.scoping.ids), np.asarray(sef.data).reshape(-1, 6)
            kpe = len(np.asarray(sef.get_entity_data(0)).reshape(-1, 6)) if len(se_ids) else 0
            if len(se_ids) and len(sed) == kpe * len(se_ids):  # same number of nodes in every element
                vme = principal_and_vm(sed)[3].reshape(len(se_ids), kpe)
                emean, emax = vme.mean(1), vme.max(1)
            else:  # mixed element types: element by element
                emean, emax = np.empty(len(se_ids)), np.empty(len(se_ids))
                for j in range(len(se_ids)):
                    vv = principal_and_vm(np.asarray(sef.get_entity_data(j)).reshape(-1, 6))[3]
                    emean[j], emax[j] = vv.mean(), vv.max()
            emap = dict(zip(se_ids.tolist(), range(len(se_ids))))
            idx = np.array([emap.get(e, -1) for e in elem_ids[gcell].tolist()])
            v["_elem_mean"] = np.where(idx >= 0, emean[idx], np.nan)
            v["_elem_max"] = np.where(idx >= 0, emax[idx], np.nan)
            if t_fc is not None:
                v["temperature"] = fill_midside(scatter(t_fc.get_field_by_time_id(s), 1), blocks)[:, 0]
                temps_by_part.append(v["temperature"][part_nodes])
            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)

    # temperature only if it actually varies (a uniform reference temperature carries no information)
    has_temp = bool(temps_by_part) and np.nanmax([np.nanmax(t) for t in temps_by_part]) > \
        np.nanmin([np.nanmin(t) for t in temps_by_part])
    if temp_result and not has_temp:
        log(f"'{temp_result}' is uniform -> temperature not included")

    # ---------------- beam connections (bolts): line cells, deformation only
    beam_cells = np.where(roles == "line")[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)  # quadratic edge: end, mid, end
            segs += [(n[i], n[i + 1]) for i in range(len(n) - 1)]
            seg_elem += [elem_ids[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})

    # point ranges of every part inside the .vtp (parts are appended in order, points never shared)
    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)

    # ---------------- named selections (Ansys components; Mechanical's internal ones start with "_")
    # Every named selection is stored as a node or an element component, whatever it was made from
    # (body, face, edge, vertex, element set). "ids" keeps only the nodes / elements present in the
    # package (outer surface + beams), enough to highlight it; max/min use all of its nodes.
    named = []
    try:
        ns_names = [n for n in model.metadata.available_named_selections if not n.startswith("_")]
    except Exception as e:
        log(f"Named selections could not be read ({e})")
        ns_names = []
    if ns_names:
        surf_nodes = np.unique(np.concatenate([node_nums[g] for _, g, _ in surfaces]
                                              + ([node_nums[beam[1]]] if beam else [])))
        surf_elems = np.unique(np.concatenate([np.asarray(sf.cell_data["ansys_elem_num"]) for sf, _, _ in surfaces]
                                              + ([np.asarray(beam[0].cell_data["ansys_elem_num"])] if beam else [])))
        elem_order = np.argsort(elem_ids)
        for nsn in ns_names:
            sc = model.metadata.named_selection(nsn)
            ids = np.unique(np.asarray(sc.ids, dtype=np.int64))
            if not len(ids):
                continue
            is_elem = "elem" in str(sc.location).lower()
            if is_elem:
                pos = np.searchsorted(elem_ids[elem_order], ids)
                ok = pos < len(elem_ids)
                ok[ok] = elem_ids[elem_order][pos[ok]] == ids[ok]
                cells = elem_order[pos[ok]]
                nodes = np.unique(np.concatenate([conn[offs[c]:offs[c + 1]] for c in cells])) if len(cells) else \
                    np.zeros(0, dtype=np.int64)
                show = np.intersect1d(ids, surf_elems)
            else:
                pos = np.searchsorted(sorted_nums, ids)
                ok = pos < len(sorted_nums)
                ok[ok] = sorted_nums[pos[ok]] == ids[ok]
                nodes = np.unique(order[pos[ok]])
                show = np.intersect1d(ids, surf_nodes)
            named.append({"name": nsn, "type": "elements" if is_elem else "nodes", "count": int(len(ids)),
                          "ids": show.astype(int).tolist(),
                          "_part_nodes": [np.intersect1d(nodes, pn) for _, _, pn in surfaces]})
            log(f"Named selection '{nsn}': {len(ids)} {'elements' if is_elem else 'nodes'} "
                f"({len(show)} on the displayed surface)")

    # ---------------- fields
    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 part_values and all("equivalent_elastic_strain" in vals[0] for vals in part_values):
        fields.append({"name": "equivalent_elastic_strain", "label": "Equivalent Elastic Strain",
                       "unit": strain_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"]

    # ---------------- one .vtp per result set
    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:
        # section view: volume mesh once per body (coordinates float32 n*3, then tetrahedra uint32 m*4)
        section_meta = None
        if section_parts:
            sp_meta = []
            for sp in section_parts:
                f = f"section/part_{sp['pid']:03d}.bin"
                zf.writestr(f, coords[sp["nodes"]].astype("<f4").tobytes() + sp["tets"].astype("<u4").tobytes())
                sp_meta.append({"part_id": sp["pid"], "n_nodes": int(len(sp["nodes"])), "n_tets": int(len(sp["tets"])),
                                "file": f})
            section_meta = {"version": 1, "fields": scalar_names, "parts": sp_meta}
            log(f"Section view data: {sum(p_['n_nodes'] for p_ in sp_meta)} nodes, "
                f"{sum(p_['n_tets'] for p_ in sp_meta)} tetrahedra")
        sec_index = {sp["pid"]: sp for sp in section_parts}
        for k, s in enumerate(sets):
            u = U[k]
            umag = np.linalg.norm(u, axis=1)
            pieces, step_parts, overall, ns_stats = [], {}, {}, {}
            sec_values = {}
            for pi, (p, (surf, gidx, part_nodes), vals) in enumerate(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)
                if p["id"] in sec_index:                          # section view: values at every node of the body
                    nodes = sec_index[p["id"]]["nodes"]
                    sec_values[p["id"]] = u[nodes].astype("<f4").tobytes() + b"".join(
                        v[nm][nodes].astype("<f4").tobytes() for nm in scalar_names)
                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])
                for ns in named:                                  # max / min within each named selection
                    pn = ns["_part_nodes"][pi]
                    if len(pn):
                        d = ns_stats.setdefault(ns["name"], {})
                        for nm in stat_names:
                            d[nm] = merge_stats(d.get(nm), stats_of(v[nm], pn, node_nums, coords, u))
            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 = lsss.get(s, (None, None))
            steps.append({"set": s, "time": float(times[k]), "load_step": ls, "substep": ss, "file": fname,
                          "fields": overall, "parts": step_parts, "named_selections": ns_stats})
            if section_meta:   # per body: displacement float32 n*3, then every scalar field float32 n
                steps[-1]["section_file"] = f"section/step_{s:03d}.bin"
                zf.writestr(steps[-1]["section_file"], b"".join(sec_values[sp["pid"]] for sp in section_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']})")

        analysis = str(ri.analysis_type)
        meta = {
            "package_version": PACKAGE_VERSION,
            "source_file": os.path.basename(rst),  # file name only, never the local path
            "model_name": name or model_name_for(rst, ri.main_title),
            "title": (ri.main_title or "").strip(),
            "analysis_type": ANALYSIS_NAMES.get(analysis, analysis),
            "solver": str(ri.product_name),
            "solver_version": str(ri.solver_version),
            "converter": CONVERTER,
            "converter_version": f"ansys-dpf-core {dpf.__version__}",
            "created": time.strftime("%Y-%m-%dT%H:%M:%S"),
            "unit_system": str(ri.unit_system_name),
            "units": {**{f["name"]: f["unit"] for f in fields},
                      "length": str(mesh.unit), "time": time_unit},
            "time_quantity": "Frequency" if analysis in ("modal", "harmonic") else "Time",
            "averaging": "nodal, per body (no averaging across bodies)",
            "n_nodes": int(len(node_nums)),
            "n_elements": int(len(elem_ids)),
            "fields": fields,
            "parts": parts,
            "named_selections": [{k_: v_ for k_, v_ in ns.items() if not k_.startswith("_")} for ns in named],
            "materials": material_list(parts, parse_matml(os.path.join(os.path.dirname(os.path.abspath(rst)), "MatML.xml"))),
            "section": section_meta,
            "steps": steps,
        }
        zf.writestr("metadata.json", json.dumps(meta, indent=1))

    # ---------------- summary
    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']})")
    return meta


def main():
    ap = argparse.ArgumentParser(description="Convert an Ansys .rst file into a SimViewer package (.zip) with PyDPF.")
    ap.add_argument("rst", help="Ansys result file (.rst)")
    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 (default: from the Mechanical project folder)")
    a = ap.parse_args()
    if not os.path.isfile(a.rst):
        sys.exit(f"File not found: {a.rst}")
    out = a.output or os.path.splitext(os.path.basename(a.rst))[0] + "_simviewer.zip"
    convert(a.rst, out, a.name)


if __name__ == "__main__":
    main()
