"""Cross-chunk boundary handling: splitting, partitioning, and linking.

All functions are pure numpy.  They take vertex positions and chunk
assignments as input and produce the data structures needed to write
cross-chunk links, partition edges/faces into intra- vs inter-chunk,
and split ordered polylines at chunk boundaries.
"""

from __future__ import annotations

import math
from collections.abc import Sequence

import numpy as np
import numpy.typing as npt

from zarr_vectors.core.paths import format_offsets
from zarr_vectors.exceptions import ChunkingError
from zarr_vectors.typing import ChunkCoords, ChunkShape, CrossChunkLink

# ===================================================================
# Polyline / streamline splitting
# ===================================================================

def split_polyline_at_boundaries(
    vertices: npt.NDArray[np.floating],
    chunk_shape: ChunkShape,
) -> list[tuple[ChunkCoords, npt.NDArray[np.floating]]]:
    """Split an ordered polyline into segments at chunk boundaries.

    Consecutive vertices in the same chunk form one segment.  The
    returned list preserves the original vertex order — concatenating
    all segment arrays recovers the input.

    Args:
        vertices: ``(N, D)`` ordered vertex positions.
        chunk_shape: Physical chunk size per dimension.

    Returns:
        List of ``(chunk_coords, segment_vertices)`` in polyline order.
        Each ``segment_vertices`` is ``(N_k, D)``.

    Raises:
        ChunkingError: If vertices is empty or dimensions mismatch.
    """
    if len(vertices) == 0:
        return []

    ndim = vertices.shape[1]
    if len(chunk_shape) != ndim:
        raise ChunkingError(
            f"chunk_shape length {len(chunk_shape)} != vertex ndim {ndim}"
        )

    cs = np.array(chunk_shape, dtype=np.float64)
    # Compute chunk coords for every vertex — vectorised
    chunk_ints = np.floor(vertices / cs).astype(np.int64)  # (N, D)

    # Find where chunk coords change between consecutive vertices
    changes = np.any(chunk_ints[1:] != chunk_ints[:-1], axis=1)  # (N-1,)
    boundaries = np.flatnonzero(changes) + 1  # indices where new segment starts

    # Split vertex array at boundaries
    segments_idx = np.split(np.arange(len(vertices)), boundaries)

    result: list[tuple[ChunkCoords, npt.NDArray[np.floating]]] = []
    for seg_indices in segments_idx:
        if len(seg_indices) == 0:
            continue
        first = seg_indices[0]
        coord = tuple(int(x) for x in chunk_ints[first])
        result.append((coord, vertices[seg_indices]))

    return result


def cross_chunk_links_for_segments(
    segments: list[tuple[ChunkCoords, npt.NDArray[np.floating]]],
    fragment_indices: list[int],
) -> list[CrossChunkLink]:
    """Compute cross-chunk links connecting adjacent polyline segments.

    The link connects the last vertex of segment k to the first vertex
    of segment k+1 (using local indices within each fragment).

    Args:
        segments: Output of :func:`split_polyline_at_boundaries`.
        fragment_indices: Fragment index assigned to each segment within
            its chunk.  Must be same length as *segments*.

    Returns:
        List of :data:`CrossChunkLink` tuples.  Length is
        ``len(segments) - 1`` (one link per boundary crossing).

    Raises:
        ChunkingError: If lengths don't match.
    """
    if len(fragment_indices) != len(segments):
        raise ChunkingError(
            f"fragment_indices length {len(fragment_indices)} != segments length {len(segments)}"
        )

    links: list[CrossChunkLink] = []
    for i in range(len(segments) - 1):
        chunk_a, verts_a = segments[i]
        chunk_b, verts_b = segments[i + 1]
        # Last vertex of segment i (local index within fragment)
        last_idx_a = len(verts_a) - 1
        # First vertex of segment i+1
        first_idx_b = 0
        links.append((
            (chunk_a, last_idx_a),
            (chunk_b, first_idx_b),
        ))

    return links


# ===================================================================
# Edge partitioning (graphs)
# ===================================================================

def partition_edges(
    edges: npt.NDArray[np.integer],
    vertex_chunks: npt.NDArray[np.int64],
    vertex_local_indices: npt.NDArray[np.int64],
    chunk_coords_list: list[ChunkCoords],
    *,
    include_intra: bool = True,
) -> tuple[dict[ChunkCoords, npt.NDArray[np.int64]], list[CrossChunkLink]]:
    """Partition edges into intra-chunk and cross-chunk.

    Args:
        edges: ``(M, 2)`` global vertex index pairs.
        vertex_chunks: ``(N,)`` array where ``vertex_chunks[i]`` is the
            index into *chunk_coords_list* for vertex *i*.
        vertex_local_indices: ``(N,)`` array where
            ``vertex_local_indices[i]`` is vertex *i*'s local index
            within its chunk's fragment.
        chunk_coords_list: Ordered list of unique chunk coordinates.
            ``vertex_chunks[i]`` indexes into this list.
        include_intra: When ``False``, skip building the per-chunk
            intra-edge dict and return ``{}`` for it.  Callers that only
            need ``cross_links`` (e.g. the skeleton writer, which stores
            intra branch links from a separate partition) avoid the
            redundant ``np.unique`` grouping over the full edge set.

    Returns:
        intra_edges: Dict mapping ``chunk_coords`` → ``(M_local, 2)``
            array of local-index edge pairs (both endpoints in this chunk).
            Empty when ``include_intra=False``.
        cross_links: List of :data:`CrossChunkLink` for edges spanning
            chunk boundaries.
    """
    src = edges[:, 0]
    dst = edges[:, 1]

    src_chunk = vertex_chunks[src]  # (M,)
    dst_chunk = vertex_chunks[dst]  # (M,)

    same_chunk = src_chunk == dst_chunk  # (M,)

    # --- Intra-chunk edges ---
    intra: dict[ChunkCoords, list[tuple[int, int]]] = {}
    if include_intra:
        intra_edges_global = edges[same_chunk]
        intra_src_chunk = src_chunk[same_chunk]
        # Vectorised: group by chunk
        for chunk_idx in np.unique(intra_src_chunk):
            mask_c = intra_src_chunk == chunk_idx
            e_global = intra_edges_global[mask_c]
            # Remap to local indices
            local_src = vertex_local_indices[e_global[:, 0]]
            local_dst = vertex_local_indices[e_global[:, 1]]
            local_edges = np.stack([local_src, local_dst], axis=1)
            coord = chunk_coords_list[int(chunk_idx)]
            intra[coord] = local_edges

    # --- Cross-chunk edges ---
    cross_mask = ~same_chunk
    cross_edges = edges[cross_mask]
    cross_src_chunk = src_chunk[cross_mask]
    cross_dst_chunk = dst_chunk[cross_mask]

    # Convert numpy → Python lists in one C-level pass; per-element int()
    # conversions inside a Python for-loop dominate runtime otherwise.
    src_chunk_list = cross_src_chunk.tolist()
    dst_chunk_list = cross_dst_chunk.tolist()
    local_a_list = vertex_local_indices[cross_edges[:, 0]].tolist()
    local_b_list = vertex_local_indices[cross_edges[:, 1]].tolist()
    cross_links: list[CrossChunkLink] = [
        ((chunk_coords_list[ca], la), (chunk_coords_list[cb], lb))
        for ca, la, cb, lb in zip(
            src_chunk_list, local_a_list, dst_chunk_list, local_b_list,
        )
    ]

    return intra, cross_links


def partition_cross_level_edges(
    edges: npt.NDArray[np.integer],
    src_vertex_chunks: npt.NDArray[np.int64],
    src_vertex_local_indices: npt.NDArray[np.int64],
    src_chunk_coords_list: list[ChunkCoords],
    tgt_vertex_chunks: npt.NDArray[np.int64],
    tgt_vertex_local_indices: npt.NDArray[np.int64],
    tgt_chunk_coords_list: list[ChunkCoords],
) -> tuple[dict[ChunkCoords, npt.NDArray[np.int64]], list[CrossChunkLink]]:
    """Partition cross-pyramid-level edges into chunk-aligned + cross-chunk.

    Unlike :func:`partition_edges` (which operates within a single
    resolution level), this helper classifies edges whose endpoints
    live in *different* resolution levels.  Source-side endpoint
    indices (column 0 of ``edges``) are interpreted against
    ``src_vertex_chunks`` / ``src_vertex_local_indices`` /
    ``src_chunk_coords_list``; target-side endpoint indices (column 1)
    use the ``tgt_*`` tables.

    An edge is classified as **chunk-aligned** when its source chunk
    coordinates equal its target chunk coordinates; those rows are
    bucketed by source chunk and returned in ``aligned``.  Otherwise the
    edge is **cross-chunk** and returned in ``cross``.  Callers persist
    both through the merged ``links/<delta>/<offsets>/`` family at the
    source level (aligned rows at the all-zero offset, cross rows at the
    relative offset between the endpoints' chunks); this helper only
    partitions and never writes.

    Args:
        edges: ``(M, 2)`` integer pairs.  Column 0 is the source-level
            global vertex index; column 1 is the target-level global
            vertex index.
        src_vertex_chunks, src_vertex_local_indices, src_chunk_coords_list:
            Source-level chunk-mapping tables, in the same shape as the
            arguments to :func:`partition_edges`.
        tgt_vertex_chunks, tgt_vertex_local_indices, tgt_chunk_coords_list:
            Same triple for the target level.

    Returns:
        aligned: Dict mapping source ``chunk_coords`` → ``(M_aligned, 2)``
            array of ``(src_local_idx, tgt_local_idx)`` rows.
        cross: List of :data:`CrossChunkLink` for edges where the
            source and target chunk_keys differ.  Endpoint A is the
            source side at the owning level; endpoint B is the target
            side at ``this_level + delta``.
    """
    src = edges[:, 0]
    dst = edges[:, 1]

    src_chunk = src_vertex_chunks[src]
    dst_chunk = tgt_vertex_chunks[dst]

    src_cc = [src_chunk_coords_list[int(i)] for i in src_chunk]
    dst_cc = [tgt_chunk_coords_list[int(i)] for i in dst_chunk]

    aligned: dict[ChunkCoords, list[tuple[int, int]]] = {}
    cross: list[CrossChunkLink] = []

    for i in range(len(edges)):
        s, d = int(src[i]), int(dst[i])
        cc_s = src_cc[i]
        cc_d = dst_cc[i]
        local_s = int(src_vertex_local_indices[s])
        local_d = int(tgt_vertex_local_indices[d])
        if cc_s == cc_d:
            aligned.setdefault(cc_s, []).append((local_s, local_d))
        else:
            cross.append(((cc_s, local_s), (cc_d, local_d)))

    aligned_arr: dict[ChunkCoords, npt.NDArray[np.int64]] = {
        cc: np.asarray(rows, dtype=np.int64) for cc, rows in aligned.items()
    }
    return aligned_arr, cross


def partition_faces(
    faces: npt.NDArray[np.integer],
    vertex_chunks: npt.NDArray[np.int64],
    vertex_local_indices: npt.NDArray[np.int64],
    chunk_coords_list: list[ChunkCoords],
) -> tuple[
    dict[ChunkCoords, npt.NDArray[np.int64]],
    list[list[tuple[ChunkCoords, int]]],
]:
    """Partition faces into intra-chunk and cross-chunk.

    Args:
        faces: ``(F, L)`` global vertex index array.  L=3 for triangles,
            L=4 for quads.
        vertex_chunks: ``(N,)`` chunk index per vertex.
        vertex_local_indices: ``(N,)`` local index per vertex.
        chunk_coords_list: Ordered unique chunk coordinates.

    Returns:
        intra_faces: Dict mapping ``chunk_coords`` → ``(F_local, L)``
            array of local-index face definitions.
        cross_faces: List of cross-chunk face references.  Each element
            is a list of ``L`` tuples ``(chunk_coords, local_vertex_index)``
            — one per face vertex.
    """
    f_count, lo = faces.shape

    # Get chunk index for every vertex of every face
    face_chunks = vertex_chunks[faces]  # (F, L)

    # A face is intra-chunk if all vertices are in the same chunk
    all_same = np.all(face_chunks == face_chunks[:, :1], axis=1)  # (F,)

    # --- Intra-chunk faces ---
    intra_faces = faces[all_same]
    intra_chunk_ids = face_chunks[all_same, 0]

    intra: dict[ChunkCoords, npt.NDArray[np.int64]] = {}
    for chunk_idx in np.unique(intra_chunk_ids):
        mask = intra_chunk_ids == chunk_idx
        f_global = intra_faces[mask]
        # Remap all vertices to local indices
        local_f = vertex_local_indices[f_global]
        coord = chunk_coords_list[int(chunk_idx)]
        intra[coord] = local_f

    # --- Cross-chunk faces ---
    cross_face_indices = np.flatnonzero(~all_same)
    cross_faces_global = faces[cross_face_indices]                   # (F_cross, L)
    cross_chunk_ids = vertex_chunks[cross_faces_global].tolist()     # nested Python ints
    cross_local_ids = vertex_local_indices[cross_faces_global].tolist()
    cross: list[list[tuple[ChunkCoords, int]]] = [
        [(chunk_coords_list[ci], li) for ci, li in zip(row_chunks, row_locals)]
        for row_chunks, row_locals in zip(cross_chunk_ids, cross_local_ids)
    ]

    return intra, cross


# ===================================================================
# Canonical chunk-tuple sort + Lehmer-coded permutation
# ===================================================================
#
# A link record is a list of L (chunk_coords, vertex_idx) endpoints.
# Under the offset layout a record is stored in the array
# ``links/<delta>/<offsets>/`` at the cell of its *source* chunk — the
# first endpoint of the chosen placement — where ``<offsets>`` names
# where the remaining endpoints sit relative to that source (see
# :func:`zarr_vectors.core.paths.format_offsets`).  A record whose
# endpoints all share one chunk has all-zero offsets: that is the
# intra-chunk array, and it needs no sort and no ``perm_idx``.
#
# For genuinely cross-chunk records we lex-sort the L endpoints by
# ``(chunk_coords, vertex_idx)`` so that each undirected record is
# stored exactly once, under the lexicographically-positive offset.
#
# That sort is destructive of the input endpoint order — but mesh face
# winding and directed-graph edge direction depend on it.  We preserve
# it by storing one ``perm_idx`` int per record: the Lehmer code of the
# permutation ``sorted_idx`` that maps canonical position i back to the
# original input position (``input[sorted_idx[i]] == canonical[i]``).
#
# Lehmer codes pack a permutation of length L into an integer in
# ``[0, L!)``.  L=1 → 1 code, L=2 → 2, L=3 → 6, L=4 → 24 — all fit
# comfortably in an int64 slot.


def anchor_chunk(
    chunk: ChunkCoords,
    scale_src: Sequence[int],
    scale_trg: Sequence[int],
) -> ChunkCoords:
    """Express a source chunk coord in the *target* level's chunk grid.

    Chunk coords are indices into a level's grid, so when two levels
    carry different ``chunk_shape`` (a per-level override — see
    :func:`zarr_vectors.core.metadata.chunk_scale_factor`) their coords
    are **not** commensurable and differencing them directly is
    meaningless.  Re-anchoring the source into the target's grid makes
    the subtraction well-defined:

        anchor = floor(c_src * r_src / r_trg)
        offset = c_trg - anchor          # decode: c_trg = anchor + offset

    where ``r_L`` is level L's chunk_shape as an integer multiple of the
    root chunk_shape.  When ``r_src == r_trg`` — same level, or any
    pyramid built with the default ``chunk_scale_factor=1`` — this
    reduces to ``anchor == chunk`` and the offset is the plain
    difference.  So it is a strict generalisation, not a special case.

    Uses integer floor division: exact for large coords (no float
    rounding) and floors toward -inf, which is what negative chunk
    coords require.
    """
    return tuple(
        (int(c) * int(rs)) // int(rt)
        for c, rs, rt in zip(chunk, scale_src, scale_trg)
    )


def canonical_sort(
    record: Sequence[tuple[ChunkCoords, int]],
) -> tuple[list[tuple[ChunkCoords, int]], int]:
    """Lex-sort a record's endpoints and return ``(sorted, perm_idx)``.

    ``perm_idx`` is the Lehmer code of the permutation
    ``sorted_idx`` such that ``input[sorted_idx[i]] == sorted[i]``
    for all ``i``.  Pass it to :func:`apply_perm_inverse` on read
    to recover the original endpoint order.
    """
    L = len(record)
    if L == 0:
        raise ValueError("canonical_sort requires a non-empty record")
    sort_keys = [(tuple(c), int(v)) for c, v in record]
    indexed = sorted(range(L), key=lambda i: sort_keys[i])
    sorted_record = [(tuple(record[j][0]), int(record[j][1])) for j in indexed]
    perm_idx = _lehmer_encode(indexed)
    return sorted_record, perm_idx


def apply_perm_inverse(
    sorted_vals: Sequence, perm_idx: int, L: int,
) -> list:
    """Recover the original input order from canonical-sorted values.

    Given ``sorted_vals`` of length L and the ``perm_idx`` produced
    by :func:`canonical_sort`, returns the values in their original
    input order.
    """
    if len(sorted_vals) != L:
        raise ValueError(
            f"apply_perm_inverse: len(sorted_vals)={len(sorted_vals)} "
            f"!= L={L}"
        )
    sorted_idx = _lehmer_decode(perm_idx, L)
    # sorted_idx[i] = original input position of canonical-position-i.
    # Therefore input[sorted_idx[i]] = sorted_vals[i].
    out = [None] * L
    for i in range(L):
        out[sorted_idx[i]] = sorted_vals[i]
    return out


def _lehmer_encode(perm: Sequence[int]) -> int:
    """Encode a permutation of ``range(L)`` as an integer in ``[0, L!)``."""
    L = len(perm)
    available = list(range(L))
    code = 0
    fact = math.factorial(L)
    for i in range(L):
        fact //= (L - i)
        idx = available.index(perm[i])
        code += idx * fact
        available.pop(idx)
    return code


def _lehmer_decode(code: int, L: int) -> list[int]:
    """Inverse of :func:`_lehmer_encode`."""
    if L < 1:
        raise ValueError(f"L must be >= 1, got {L}")
    upper = math.factorial(L)
    if not (0 <= code < upper):
        raise ValueError(
            f"perm_idx {code} out of range [0, {L}!) = [0, {upper})"
        )
    available = list(range(L))
    perm = [0] * L
    fact = upper
    for i in range(L):
        fact //= (L - i)
        idx = code // fact
        code %= fact
        perm[i] = available[idx]
        available.pop(idx)
    return perm


def _cell_placements(
    record: Sequence[tuple[ChunkCoords, int]],
    *,
    directed: bool,
    store: str,
    cross_level: bool = False,
) -> list[list[int]]:
    """Return the storage permutations a record is filed under.

    Each returned ``sigma`` is a permutation of ``range(L)``: the record
    is stored at the cell of ``chunk(sigma[0])`` — the *source* — in the
    array whose offsets are ``chunk(sigma[k]) - anchor(source)`` for
    ``k > 0``, with vertex indices ``[vi(sigma[0]), ...]`` and
    ``perm_idx = _lehmer_encode(sigma)``, so :func:`apply_perm_inverse`
    recovers the original input order from any copy.

    Identity placement (``sigma = range(L)``, ``perm_idx = 0``) is forced
    in two cases, regardless of ``directed`` / ``store``:

    - **Intra-chunk records** (every endpoint in one chunk).  Their
      offsets are all zero, so there is nothing to canonicalise: sorting
      would reorder endpoints and cost a ``perm_idx`` column for no
      benefit.  Preserving input order here is what keeps the all-zero
      offsets array byte-identical to the pre-merge ``links/<delta>/``
      (polyline traversal order, for instance, is data).
    - **Cross-level records** (``cross_level=True``, i.e. ``delta != 0``).
      Endpoint 0 lives at the owning level and endpoints 1..L-1 at
      ``owning + delta``, so the endpoints are already distinguished by
      *level*, not by coord order — a canonical sort dedupes nothing
      (``A→B`` and ``B→A`` live in different delta arrays at different
      levels).  It would only risk promoting a target-level endpoint to
      source, which flips the anchor's scale factors.  Leading with
      endpoint 0 keeps the source at the owning level.

    Otherwise:

    - ``store="canonical"`` → one placement:
        * ``directed=False``: ``sigma`` is the argsort of the endpoints by
          ``(chunk_coords, vi)`` — the canonical order (identical to
          :func:`canonical_sort`) — which is what makes the stored offset
          lexicographically positive, so each undirected record is stored
          exactly once.
        * ``directed=True``: ``sigma`` is the identity — input endpoint
          order is preserved, so ``A→B`` and ``B→A`` file under opposite
          offsets (``0.0.+1`` vs ``0.0.-1``) at different cells, and
          ``perm_idx`` is 0.
    - ``store="duplicate"`` → one placement per *distinct* endpoint chunk:
      that chunk becomes the source, the remaining endpoints follow in
      ascending input-position order.  ``K`` placements where ``K`` is the
      number of distinct chunks the record touches, so a reader can find
      every record incident to a chunk ``C`` by scanning only ``C``'s cell
      across the offset arrays.  Records are independent physical copies;
      ``perm_idx`` recovers input order (direction / winding) in each.
    """
    L = len(record)
    identity = list(range(L))
    if cross_level:
        return [identity]
    chunks_all = [tuple(c) for c, _ in record]
    if all(c == chunks_all[0] for c in chunks_all):
        # Intra-chunk: all-zero offsets, nothing to canonicalise.
        return [identity]
    if store == "canonical":
        if directed:
            return [identity]
        keys = [(tuple(c), int(v)) for c, v in record]
        return [sorted(range(L), key=lambda i: keys[i])]
    if store == "duplicate":
        chunks = [tuple(c) for c, _ in record]
        vis = [int(v) for _, v in record]
        placements: list[list[int]] = []
        seen: set[ChunkCoords] = set()
        # Lead each distinct chunk once; ascending (chunk, vi) order makes
        # the emitted cell set deterministic and independent of input order.
        for lead in sorted(range(L), key=lambda i: (chunks[i], vis[i])):
            if chunks[lead] in seen:
                continue
            seen.add(chunks[lead])
            rest = [i for i in range(L) if i != lead]
            placements.append([lead] + rest)
        return placements
    raise ChunkingError(
        f"partition_records_by_offset: unknown store {store!r}; "
        f"expected 'canonical' or 'duplicate'"
    )


def partition_records_by_offset(
    records: Sequence[Sequence[tuple[ChunkCoords, int]]],
    link_width: int,
    sid_ndim: int,
    *,
    scale_src: Sequence[int],
    scale_trg: Sequence[int],
    directed: bool = False,
    store: str = "canonical",
    cross_level: bool = False,
) -> dict[tuple[str, ChunkCoords], list[tuple[list[int], int, int]]]:
    """Group link records into ``(offsets_segment, source_chunk)`` buckets.

    This is the single choke point that decides *where* a record is
    stored.  For each record and each storage permutation ``sigma``
    chosen by :func:`_cell_placements`:

    - the source chunk is ``chunk(sigma[0])`` — that is the array cell,
    - the offsets are ``chunk(sigma[k]) - anchor(source)`` for ``k > 0``,
      re-anchored across levels by :func:`anchor_chunk`,
    - ``(vi_in_source_order, perm_idx, input_index)`` is emitted into the
      bucket for that ``(offsets_segment, source_chunk)``.

    Intra-chunk records fall out naturally as all-zero offsets — they are
    not a separate family.

    Within a bucket, entries preserve input record ordering — callers
    relying on row-aligned attribute arrays can depend on this.  In
    ``store="duplicate"`` the same ``input_index`` appears under several
    buckets, so a parallel attribute array replicates identically.

    Args:
        records: List of records; each record is a sequence of
            ``(chunk_coords, vertex_idx)`` tuples of length
            ``link_width``.
        link_width: Endpoints per record.  Records of any other
            arity raise ``ChunkingError``.
        sid_ndim: Number of spatial index dimensions; every
            ``chunk_coords`` must have this arity.
        scale_src: Per-axis chunk-scale factor of the level the source
            endpoint lives at (all-ones for a default pyramid).
        scale_trg: Per-axis chunk-scale factor of the level the non-source
            endpoints live at.  Equal to ``scale_src`` when
            ``cross_level`` is False.  See :func:`anchor_chunk` — passing
            these wrong silently mis-places cross-level records on a
            store built with ``chunk_scale_factor > 1``.
        directed: When ``True``, keep input endpoint order (no canonical
            sort); ``A→B`` and ``B→A`` land under opposite offsets.  See
            :func:`_cell_placements`.
        store: ``"canonical"`` (default, one bucket per record) or
            ``"duplicate"`` (one bucket per distinct incident chunk).
        cross_level: True for ``delta != 0``; forces the source to be
            input endpoint 0 so the anchor's ``scale_src`` is the owning
            level's.  See :func:`_cell_placements`.

    Returns:
        Dict mapping ``(offsets_segment, source_chunk)`` → list of
        ``(vi_in_source_order, perm_idx, input_index)`` tuples.
        ``vi_in_source_order`` is a length-L list of int vertex indices
        in the placement's endpoint order.
    """
    if len(scale_src) != sid_ndim or len(scale_trg) != sid_ndim:
        raise ChunkingError(
            f"partition_records_by_offset: scale_src/scale_trg rank "
            f"{len(scale_src)}/{len(scale_trg)} != sid_ndim {sid_ndim}"
        )
    buckets: dict[tuple[str, ChunkCoords], list[tuple[list[int], int, int]]] = {}
    # Three per-call memos. Each of these is a pure function of something
    # a record repeats constantly: the chunk it is anchored from, the
    # permutation that placed it, and the neighbour offsets that decide
    # which array it lands in. A level has far fewer distinct chunks than
    # records, only ``L!`` permutations, and a handful of neighbour
    # patterns -- but formatting the offsets alone built a string per
    # record, which profiling put at a tenth of a pyramid build.
    #
    # Deliberately plain dicts scoped to this call, not ``lru_cache``:
    # measured, a module-level cache was *slower*, because an eviction
    # policy and a lock cost more than the arithmetic they were avoiding
    # once the key space exceeded the cache.
    anchors: dict[ChunkCoords, ChunkCoords] = {}
    perms: dict[tuple[int, ...], int] = {}
    segments: dict[tuple[ChunkCoords, ...], str] = {}
    for input_idx, rec in enumerate(records):
        rec = list(rec)
        if len(rec) != link_width:
            raise ChunkingError(
                f"partition_records_by_offset: record arity "
                f"{len(rec)} != link_width {link_width}"
            )
        for chunk, _vi in rec:
            if len(chunk) != sid_ndim:
                raise ChunkingError(
                    f"partition_records_by_offset: chunk_coords "
                    f"arity {len(chunk)} != sid_ndim {sid_ndim}"
                )
        for sigma in _cell_placements(
            rec, directed=directed, store=store, cross_level=cross_level,
        ):
            src_chunk = tuple(int(x) for x in rec[sigma[0]][0])
            anchor = anchors.get(src_chunk)
            if anchor is None:
                anchor = anchor_chunk(src_chunk, scale_src, scale_trg)
                anchors[src_chunk] = anchor
            offsets = tuple(
                tuple(int(c) - int(a) for c, a in zip(rec[j][0], anchor))
                for j in sigma[1:]
            )
            vi_in_src = [int(rec[j][1]) for j in sigma]
            sigma_key = tuple(sigma)
            perm_idx = perms.get(sigma_key)
            if perm_idx is None:
                perm_idx = _lehmer_encode(sigma)
                perms[sigma_key] = perm_idx
            segment = segments.get(offsets)
            if segment is None:
                segment = format_offsets(offsets)
                segments[offsets] = segment
            buckets.setdefault((segment, src_chunk), []).append(
                (vi_in_src, perm_idx, input_idx)
            )
    return buckets


def partition_arrays_by_offset(
    src_chunks: npt.NDArray[np.int64],
    src_vi: npt.NDArray[np.int64],
    trg_chunks: npt.NDArray[np.int64],
    trg_vi: npt.NDArray[np.int64],
    *,
    scale_src: Sequence[int],
    scale_trg: Sequence[int],
    sid_ndim: int,
) -> dict[tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]]:
    """:func:`partition_records_by_offset` for two-endpoint records held as arrays.

    A sibling rather than a mode, because the tuple signature cannot
    express the array form and the general function has to keep serving
    the mesh and skeleton writers.

    This covers exactly the shape a pyramid emits -- ``link_width=2``,
    ``directed=True``, and a cross-level ``delta`` -- and that shape is
    what makes it expressible as array work at all:
    :func:`_cell_placements` returns the identity placement
    unconditionally when ``cross_level`` is set, deciding it before it
    looks at a record, and :func:`links_has_perm` is then False, so
    there is one placement per record, a constant permutation index of
    zero, and no permutation column. What is left is arithmetic:
    floor-divide the anchor, subtract the offsets, group by the pair.

    The general function spends about ten Python objects per record on
    exactly this, and a pyramid emits one record per fine vertex --
    twice, under the default explicit storage.

    Args:
        src_chunks: ``(M, sid_ndim)`` chunk coords of endpoint 0, the
            one that leads and stays at the owning level.
        src_vi: ``(M,)`` vertex index of endpoint 0, local to its chunk.
        trg_chunks: ``(M, sid_ndim)`` chunk coords of endpoint 1.
        trg_vi: ``(M,)`` vertex index of endpoint 1, local to its chunk.
        scale_src: Source level's chunk scale, per axis.
        scale_trg: Target level's chunk scale, per axis.
        sid_ndim: Spatial index dimensionality.

    Returns:
        ``{(offsets_segment, source_chunk): (rows, input_indices)}``,
        where ``rows`` is ``(M_k, 2)`` of ``[src_vi, trg_vi]`` and
        ``input_indices`` says which input record each row came from.
        Rows keep their input order within a bucket, which is what makes
        the output byte-identical to the record-shaped function's.
    """
    src_chunks = np.asarray(src_chunks, dtype=np.int64)
    trg_chunks = np.asarray(trg_chunks, dtype=np.int64)
    src_vi = np.asarray(src_vi, dtype=np.int64)
    trg_vi = np.asarray(trg_vi, dtype=np.int64)
    n = int(src_vi.shape[0])
    for name, arr in (("src_chunks", src_chunks), ("trg_chunks", trg_chunks)):
        if arr.ndim != 2 or arr.shape[1] != sid_ndim:
            raise ChunkingError(
                f"partition_arrays_by_offset: {name} has shape "
                f"{arr.shape}; expected (M, {sid_ndim})"
            )
    if not (src_chunks.shape[0] == trg_chunks.shape[0] == n == trg_vi.shape[0]):
        raise ChunkingError(
            "partition_arrays_by_offset: endpoint arrays disagree on length"
        )
    if n == 0:
        return {}

    # anchor = floor(c_src * r_src / r_trg), the same integer floor
    # division ``anchor_chunk`` performs, which floors toward -inf and so
    # is correct for negative coords. offset = c_trg - anchor.
    rs = np.asarray(scale_src, dtype=np.int64)
    rt = np.asarray(scale_trg, dtype=np.int64)
    offsets = trg_chunks - ((src_chunks * rs) // rt)

    # Group by (source chunk, offsets). lexsort is stable, so records
    # keep their input order inside a group.
    key = np.concatenate([src_chunks, offsets], axis=1)
    order = np.lexsort(key.T[::-1])
    key_sorted = key[order]
    rows = np.stack([src_vi, trg_vi], axis=1)[order]

    starts = np.flatnonzero(
        np.concatenate((
            [True], np.any(key_sorted[1:] != key_sorted[:-1], axis=1),
        ))
    )
    ends = np.append(starts[1:], n)

    out: dict[
        tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]
    ] = {}
    for start, end in zip(starts.tolist(), ends.tolist()):
        head = key_sorted[start]
        src_chunk = tuple(int(x) for x in head[:sid_ndim])
        offset = tuple(int(x) for x in head[sid_ndim:])
        # One format_offsets per distinct group, not per record.
        out[(format_offsets((offset,)), src_chunk)] = (
            rows[start:end], order[start:end],
        )
    return out


#: Endpoint counts the array partitioner handles.  Its permutation
#: tables are ``L**L`` and ``L!`` entries; past this a record-shaped
#: family is exotic enough that the per-record path is the right one.
_MAX_ARRAY_LINK_WIDTH = 6


def _lehmer_table(link_width: int) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
    """``(code_of, radix)`` such that ``code_of[sigma @ radix]`` is
    :func:`_lehmer_encode` of the permutation ``sigma``.

    ``sigma @ radix`` is ``sigma`` read as a base-``L`` number, which is
    injective over permutations, so a table of ``L**L`` entries answers
    every one of them with a gather.
    """
    import itertools

    L = link_width
    radix = (L ** np.arange(L - 1, -1, -1)).astype(np.int64)
    table = np.full(L ** L, -1, dtype=np.int64)
    for perm in itertools.permutations(range(L)):
        table[int(np.dot(perm, radix))] = _lehmer_encode(perm)
    return table, radix


def _pack_rows(rows: npt.NDArray[np.int64]) -> npt.NDArray[np.int64] | None:
    """Each row of a 2-D integer array as one int64, ordered as the rows
    sort lexicographically (first column most significant), or None
    when the columns' ranges do not fit in 63 bits."""
    if rows.shape[0] == 0:
        return None
    # Per column: faster than an axis-0 reduction on a narrow array.
    lo = np.array([rows[:, c].min() for c in range(rows.shape[1])], dtype=rows.dtype)
    span = np.array([rows[:, c].max() for c in range(rows.shape[1])], dtype=rows.dtype) - lo + 1
    total = 1
    for s in span.tolist():
        total *= int(s)
    if total >= (1 << 62):
        return None
    out = np.zeros(rows.shape[0], dtype=np.int64)
    for c in range(rows.shape[1]):
        out *= int(span[c])
        out += rows[:, c] - lo[c]
    return out


def partition_link_arrays(
    chunks: npt.NDArray[np.int64],
    vi: npt.NDArray[np.int64],
    *,
    link_width: int,
    sid_ndim: int,
    scale_src: Sequence[int],
    scale_trg: Sequence[int],
    directed: bool = False,
    cross_level: bool = False,
) -> dict[tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]]:
    """:func:`partition_records_by_offset` for records held as arrays,
    under ``store="canonical"``.

    The general function spends about ten Python objects per record --
    a list, its endpoint tuples, a sort key, a placement -- and a mesh
    emits one record per face: 13 s of a 74 s write for half a million
    faces, before a byte reached the store.  Every step of it is array
    arithmetic: the placement is an argsort of each record's endpoints,
    the permutation index a table gather, the anchor a floor-divide,
    the offsets a subtraction, and the bucket a group-by.

    Placement follows :func:`_cell_placements` exactly:

    - ``cross_level``, ``directed``, and intra-chunk records keep the
      input endpoint order (identity, ``perm_idx`` 0);
    - otherwise the endpoints are sorted by ``(chunk_coords, vi)``, and
      the record files under the lexicographically-positive offset once.

    ``store="duplicate"`` is not covered -- one record files under
    several cells there, which is the record function's business.

    Args:
        chunks: ``(M, L, sid_ndim)`` chunk coords of every endpoint.
        vi: ``(M, L)`` chunk-local vertex index of every endpoint.
        link_width: ``L``.
        sid_ndim: Spatial index dimensionality.
        scale_src, scale_trg: As :func:`partition_records_by_offset`.
        directed: Keep input endpoint order for every record.
        cross_level: ``delta != 0``; endpoint 0 leads unconditionally.

    Returns:
        ``{(offsets_segment, source_chunk): (rows, input_indices)}``.
        ``rows`` is the ``(M_k, W)`` block the cell stores -- the placed
        vertex indices, led by the ``perm_idx`` column exactly when
        :func:`~zarr_vectors.core.arrays.links_has_perm` says the segment
        carries one -- and ``input_indices`` says which input record each
        row came from.  Rows keep their input order within a bucket.
    """
    from zarr_vectors import _xp

    # Device arrays are partitioned where they are; what comes back is the
    # grouped rows, which the writer needs on the host anyway.
    on_device = _xp.encode_on_device(chunks, vi)
    if on_device:
        import cupy as xp
    else:
        xp = np
        chunks, vi = _xp.to_host(chunks), _xp.to_host(vi)
    chunks = xp.asarray(chunks).astype(xp.int64, copy=False)
    vi = xp.asarray(vi).astype(xp.int64, copy=False)
    L = int(link_width)
    if chunks.ndim != 3 or chunks.shape[1:] != (L, sid_ndim):
        raise ChunkingError(
            f"partition_link_arrays: chunks has shape {chunks.shape}; "
            f"expected (M, {L}, {sid_ndim})"
        )
    if vi.shape != chunks.shape[:2]:
        raise ChunkingError(
            f"partition_link_arrays: vi has shape {vi.shape}; expected "
            f"{chunks.shape[:2]}"
        )
    if len(scale_src) != sid_ndim or len(scale_trg) != sid_ndim:
        raise ChunkingError(
            f"partition_link_arrays: scale_src/scale_trg rank "
            f"{len(scale_src)}/{len(scale_trg)} != sid_ndim {sid_ndim}"
        )
    if L > _MAX_ARRAY_LINK_WIDTH:
        raise ChunkingError(
            f"partition_link_arrays: link_width {L} exceeds "
            f"{_MAX_ARRAY_LINK_WIDTH}; use partition_records_by_offset"
        )
    n = int(vi.shape[0])
    if n == 0:
        return {}

    # --- placement: which input endpoint leads, and in what order -----
    intra = xp.ones(n, dtype=bool)
    for j in range(1, L):
        for d in range(sid_ndim):
            intra &= chunks[:, j, d] == chunks[:, 0, d]
    identity = xp.arange(L, dtype=xp.int64)
    if cross_level or directed or L == 1:
        sigma = xp.broadcast_to(identity, (n, L))
    else:
        # The canonical order of each record's endpoints, by
        # (chunk_coords, vi): one lexsort over every endpoint of every
        # record with the record as primary key, stable like the sorted()
        # it replaces.  Intra-chunk records keep input order, as
        # _cell_placements does.
        packed = None if on_device else _pack_rows(
            np.concatenate([chunks, vi[:, :, None]], axis=2).reshape(-1, sid_ndim + 1)
        )
        if packed is not None:
            sigma = np.argsort(packed.reshape(n, L), axis=1, kind="stable")
        else:
            rec = xp.repeat(xp.arange(n, dtype=xp.int64), L)
            keys = [vi.reshape(-1)]
            flat_chunks = chunks.reshape(-1, sid_ndim)
            keys += [flat_chunks[:, d] for d in range(sid_ndim - 1, -1, -1)]
            keys.append(rec)
            order = xp.lexsort(xp.stack(keys))
            sigma = order.reshape(n, L) - (xp.arange(n, dtype=xp.int64) * L)[:, None]
        sigma = xp.where(intra[:, None], identity[None, :], sigma)

    rowsel = xp.arange(n, dtype=xp.int64)[:, None]
    placed_chunks = chunks[rowsel, sigma]          # (n, L, D)
    placed_vi = vi[rowsel, sigma]                  # (n, L)
    if cross_level or directed or L == 1:
        perm = xp.zeros(n, dtype=xp.int64)
    else:
        table, radix = _lehmer_table(L)
        perm = xp.asarray(table)[(sigma * xp.asarray(radix)).sum(axis=1)]

    # --- anchor and offsets -------------------------------------------
    rs = xp.asarray(np.asarray(scale_src, dtype=np.int64))
    rt = xp.asarray(np.asarray(scale_trg, dtype=np.int64))
    src = placed_chunks[:, 0, :]
    anchor = (src * rs) // rt
    offsets = placed_chunks[:, 1:, :] - anchor[:, None, :]   # (n, L-1, D)

    # --- group by (source chunk, offsets) -----------------------------
    key = xp.concatenate([src, offsets.reshape(n, -1)], axis=1)
    packed = None if on_device else _pack_rows(key)
    if packed is not None:
        # Same order as the lexsort below.
        order = np.argsort(packed, kind="stable")
        ps = packed[order]
        key_sorted = key[order]
        starts = np.flatnonzero(np.concatenate(([True], ps[1:] != ps[:-1])))
    else:
        order = xp.lexsort(key.T[::-1])
        key_sorted = key[order]
        starts = xp.flatnonzero(
            xp.concatenate((
                xp.ones(1, dtype=bool), xp.any(key_sorted[1:] != key_sorted[:-1], axis=1),
            ))
        )

    placed_vi = placed_vi[order]
    perm = perm[order]
    heads = key_sorted[starts]
    if on_device:
        # Four downloads: the grouped rows and where each group starts.
        placed_vi, perm, order, heads, starts = (
            _xp.to_host(a) for a in (placed_vi, perm, order, heads, starts)
        )
    ends = np.append(starts[1:], n)
    out: dict[
        tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]
    ] = {}
    segments: dict[tuple[int, ...], tuple[str, bool]] = {}
    # Every group's key as Python ints in one conversion; a line store
    # has a bucket per cell, a hundred thousand of them, and converting
    # each head element by element was most of this function.
    for head, start, end in zip(heads.tolist(), starts.tolist(), ends.tolist()):
        src_chunk = tuple(head[:sid_ndim])
        flat_offsets = tuple(head[sid_ndim:])
        seg = segments.get(flat_offsets)
        if seg is None:
            offset_tuples = tuple(
                flat_offsets[k * sid_ndim:(k + 1) * sid_ndim] for k in range(L - 1)
            )
            is_intra = not any(flat_offsets)
            # The perm column exists exactly where links_has_perm says:
            # never intra, never cross-level or directed, else always.
            has_perm = not (is_intra or cross_level or directed)
            seg = (format_offsets(offset_tuples), has_perm)
            segments[flat_offsets] = seg
        segment, has_perm = seg
        rows = placed_vi[start:end]
        if has_perm:
            rows = np.concatenate([perm[start:end, None], rows], axis=1)
        out[(segment, src_chunk)] = (
            np.ascontiguousarray(rows), order[start:end],
        )
    return out


def partition_link_indices(
    chunk_table: npt.NDArray[np.int64],
    cidx: npt.NDArray[np.int64],
    vi: npt.NDArray[np.int64],
    *,
    sid_ndim: int,
    intra: npt.NDArray[np.bool_] | None = None,
) -> dict[tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]]:
    """``partition_link_arrays(chunk_table[cidx], vi, ...)`` for same-level
    undirected records, with intra-chunk records grouped by a sort alone.

    Args:
        chunk_table: ``(C, sid_ndim)`` distinct chunk coords, sorted.
        cidx: ``(M, L)`` index into ``chunk_table`` of every endpoint.
        vi: ``(M, L)`` chunk-local vertex index of every endpoint.
        sid_ndim: Spatial index dimensionality.
        intra: ``(M,)`` whether a record lies in one chunk, if known.

    Returns:
        As :func:`partition_link_arrays`.
    """
    chunk_table = np.asarray(chunk_table, dtype=np.int64)
    cidx = np.asarray(cidx, dtype=np.int64)
    vi = np.asarray(vi, dtype=np.int64)
    n, L = vi.shape
    if L > _MAX_ARRAY_LINK_WIDTH:
        raise ChunkingError(
            f"partition_link_indices: link_width {L} exceeds "
            f"{_MAX_ARRAY_LINK_WIDTH}; use partition_records_by_offset"
        )
    if intra is None:
        intra = np.all(cidx == cidx[:, :1], axis=1)
    intra_idx = np.flatnonzero(intra)
    cross_idx = np.flatnonzero(~intra)
    intra_buckets: list[
        tuple[tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]]
    ] = []
    if intra_idx.size:
        src = cidx[intra_idx, 0]
        # numpy sorts 16-bit keys stably by radix, in linear time.
        key = src.astype(np.uint16) if len(chunk_table) <= (1 << 16) else src
        sort = np.argsort(key, kind="stable")
        order = intra_idx[sort]
        src = src[sort]
        rows = vi[order]
        starts = np.flatnonzero(np.concatenate(([True], src[1:] != src[:-1])))
        ends = np.append(starts[1:], order.size)
        segment = format_offsets(((0,) * sid_ndim,) * (L - 1))
        heads = chunk_table[src[starts]].tolist()
        for head, start, end in zip(heads, starts.tolist(), ends.tolist()):
            intra_buckets.append(
                ((segment, tuple(head)), (rows[start:end], order[start:end])),
            )
    cross: dict[
        tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]
    ] = {}
    if cross_idx.size:
        unit = [1] * sid_ndim
        cross = partition_link_arrays(
            chunk_table[cidx[cross_idx]], vi[cross_idx],
            link_width=L, sid_ndim=sid_ndim, scale_src=unit, scale_trg=unit,
        )
    # Merge in partition_link_arrays order; a chunk's intra bucket (zero
    # offsets) leads its crossing ones.
    out: dict[
        tuple[str, ChunkCoords], tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]
    ] = {}
    pending = iter(intra_buckets)
    nxt = next(pending, None)
    for bucket, (rows, idx) in cross.items():
        while nxt is not None and nxt[0][1] <= bucket[1]:
            out[nxt[0]] = nxt[1]
            nxt = next(pending, None)
        out[bucket] = (rows, cross_idx[idx])
    while nxt is not None:
        out[nxt[0]] = nxt[1]
        nxt = next(pending, None)
    return out


# ===================================================================
# Vertex assignment helpers
# ===================================================================

def build_vertex_chunk_mapping(
    chunk_assignments: dict[ChunkCoords, npt.NDArray[np.intp]],
    n_vertices: int,
    chunk_coords_list: list[ChunkCoords] | None = None,
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64], list[ChunkCoords]]:
    """Build per-vertex chunk index and local index arrays.

    Given the output of ``chunking.assign_chunks``, builds the arrays
    needed by :func:`partition_edges` and :func:`partition_faces`.

    Args:
        chunk_assignments: ``{chunk_coords: vertex_indices_array}``.
        n_vertices: Total number of vertices.
        chunk_coords_list: If provided, use this ordering.  Otherwise
            sorted from chunk_assignments keys.

    Returns:
        A tuple ``(vertex_chunks, vertex_local_indices, chunk_coords_list)``:

        - ``vertex_chunks``: ``(N,)`` int64, the index into
          ``chunk_coords_list`` for each vertex (``-1`` if unassigned).
        - ``vertex_local_indices``: ``(N,)`` int64, each vertex's position
          within its chunk's vertex array (``-1`` if unassigned).
        - ``chunk_coords_list``: the chunk coordinate ordering used.
    """
    if chunk_coords_list is None:
        chunk_coords_list = sorted(chunk_assignments.keys())

    coord_to_idx = {c: i for i, c in enumerate(chunk_coords_list)}

    vertex_chunks = np.full(n_vertices, -1, dtype=np.int64)
    vertex_local_indices = np.full(n_vertices, -1, dtype=np.int64)

    # Scatter per chunk rather than per vertex: the inner loop ran once
    # for every vertex in the level, on the write path of every graph and
    # mesh. A chunk's vertices are numbered 0..n-1 in the order they are
    # stored, which is an arange, and their destinations are the chunk's
    # own index array -- both expressible as one scatter each.
    for coord, global_indices in chunk_assignments.items():
        gi = np.asarray(global_indices, dtype=np.int64)
        if gi.size == 0:
            continue
        vertex_chunks[gi] = coord_to_idx[coord]
        vertex_local_indices[gi] = np.arange(gi.size, dtype=np.int64)

    if np.any(vertex_chunks == -1):
        missing = int(np.sum(vertex_chunks == -1))
        raise ChunkingError(
            f"{missing} vertices not assigned to any chunk"
        )

    return vertex_chunks, vertex_local_indices, chunk_coords_list


def chunk_local_to_global_offsets(
    level_group,
    ndim: int | None = None,
) -> tuple[dict[ChunkCoords, int], list[ChunkCoords], int]:
    """Build the per-chunk → global vertex-index offset table.

    For each chunk in a level (sorted lexicographically), returns the
    cumulative starting vertex index in a hypothetical concatenation
    of all chunks.  This is the standard input shape needed by
    algorithms that need to map ``(chunk_key, local_idx)`` to a global
    vertex ID without rebuilding the mapping themselves.

    Per-chunk vertex counts are derived from the size of each
    ``vertices/<chunk_key>`` blob divided by ``ndim * dtype.itemsize``.

    Args:
        level_group: An open :class:`FsGroup` for one resolution level.
        ndim: Coordinate columns per vertex.  ``None`` derives it from
            the store's NGFF axes.  Passing the wrong value here does not
            fail -- it silently scales every offset, which is why this
            used to be hardcoded to 3 and gave wrong answers on any 2D
            store.

    Returns:
        ``(offsets, chunk_keys, total_vertices)`` where:

        - ``offsets[chunk_key]`` = cumulative global start index for
          that chunk.
        - ``chunk_keys`` is the sorted lexicographic order used.
        - ``total_vertices`` is the sum of all per-chunk counts.
    """
    # Imported lazily to avoid circular import with core.arrays which
    # depends on this module's other helpers.
    from zarr_vectors.constants import VERTICES
    from zarr_vectors.core.arrays import (
        _chunk_key,
        _infer_vert_ndim,
        _maybe_batched_reads,
        list_chunk_keys,
    )

    chunk_keys = list_chunk_keys(level_group)
    offsets: dict[ChunkCoords, int] = {}
    running = 0

    try:
        vmeta = level_group.read_array_meta("vertices")
        dtype_str = vmeta.get("dtype", "float32")
        itemsize = np.dtype(dtype_str).itemsize
    except Exception:
        itemsize = 4  # float32 default
    ndim_meta = int(ndim) if ndim else _infer_vert_ndim(level_group)
    row_size = ndim_meta * itemsize

    # Every cell in one prefetch: sizing a level by reading its cells one
    # at a time was 10 s of a 30 s pyramid, and this runs several times
    # per build.
    keys = [_chunk_key(cc) for cc in chunk_keys]
    with _maybe_batched_reads(level_group, [(VERTICES, keys)]):
        for cc, key in zip(chunk_keys, keys):
            # Derive total vertex count from the vertices/<key> blob size.
            try:
                raw = level_group.read_bytes(VERTICES, key)
                count = len(raw) // row_size if row_size else 0
            except Exception:
                count = 0
            offsets[cc] = running
            running += int(count)
    return offsets, chunk_keys, running


def build_reindex_map(
    chunk_assignments: dict[ChunkCoords, npt.NDArray[np.intp]],
) -> dict[ChunkCoords, dict[int, int]]:
    """Build global→local index mapping per chunk.

    Args:
        chunk_assignments: ``{chunk_coords: vertex_indices_array}``.

    Returns:
        Dict mapping ``chunk_coords`` → dict of ``{global_idx: local_idx}``.
    """
    result: dict[ChunkCoords, dict[int, int]] = {}
    for coord, indices in chunk_assignments.items():
        result[coord] = {int(g): i for i, g in enumerate(indices)}
    return result
