import json


def build_address_map(tilegrid_file):
    """
    Loads the tilegrid and generates a map (baseaddr, offset) -> tile name(s).

    Parameters
    ----------

    tilegrid_file:
        The tilegrid.json file/

    Returns
    -------

    A dict with lists of tile names.

    """

    address_map = {}

    # Load tilegrid
    with open(tilegrid_file, "r") as fp:
        tilegrid = json.load(fp)

    # Loop over tiles
    for tile_name, tile_data in tilegrid.items():

        # No bits or bits empty
        if "bits" not in tile_data:
            continue
        if not len(tile_data["bits"]):
            continue

        bits = tile_data["bits"]

        # No bus
        if "CLB_IO_CLK" not in bits:
            continue

        bus = bits["CLB_IO_CLK"]

        # Make the address as integers
        baseaddr = int(bus["baseaddr"], 16)
        offset = int(bus["offset"])
        address = (
            baseaddr,
            offset,
        )

        # Add tile to the map
        if address not in address_map:
            address_map[address] = []
        address_map[address].append(tile_name)

    return address_map