import requests


def find_osm_polygon(city):
    """Interrogate the OSM nominatim API for a city polygon.

    Nominatim may not always return city matches in the most intuitive order,
    so results need to be searched for a compatible polygon. The index of the
    polygon is required for proper use of osmnx.graph_from_place(). Some cities
    do not have a polygon at all, in which case they defer to using
    graph_from_point() with city lat & lng.

    Args:
        city (str): city to search for
    Returns:
        int: index of polygon+1 (becomes the correct 'which_result' value)
        None: if no polygon found
    """

    search_params = {'format': 'json', 'limit': 5,
                     'dedupe': 0, 'polygon_geojson': 1, 'q': city}
    url = 'https://nominatim.openstreetmap.org/search'

    response = requests.get(url, params=search_params)
    for index, match in enumerate(response.json()):
        # a match that can be used by graph_from_place needs to be a Polygon
        # or MultiPolygon
        if (match['geojson']['type'] in ['Polygon', 'MultiPolygon']):
            return index+1, match['geojson']

    return None, None