from packaging.version import Version


def _build_from_h3(ids, order=1):
    """Generate Graph from H3 hexagons.

    Encode a graph from a set of H3 hexagons. The graph is generated by
    considering the H3 hexagons as nodes and connecting them based on their
    contiguity. The contiguity is defined by the order parameter, which
    specifies the number of steps to consider as neighbors.

    Requires the `h3` library.

    Parameters
    ----------
    ids : array-like
        Array of H3 IDs encoding focal geometries
    order : int, optional
        Order of contiguity, by default 1

    Returns
    -------
    tuple(dict, dict)
    """
    try:
        import h3
    except ImportError as e:
        raise ImportError(
            "This function requires the `h3` library. "
            "You can install it with `conda install h3-py` or "
            "`pip install h3`."
        ) from e

    neighbors = {}
    weights = {}
    if Version(h3.__version__) > Version("4.0"):
        for ix in ids:
            neighbors[ix] = []
            weights[ix] = []
            for i in range(1, order + 1):
                ring = h3.grid_ring(ix, i)
                neighbors[ix].extend(list(ring))
                weights[ix].extend([i] * len(ring))
    else:
        for ix in ids:
            rings = h3.hex_range_distances(ix, order)
            for i, ring in enumerate(rings):
                if i == 0:
                    neighbors[ix] = []
                    weights[ix] = []
                else:
                    neighbors[ix].extend(list(ring))
                    weights[ix].extend([i] * len(ring))

    return neighbors, weights
