import json

import numpy as np
import pyproj


def get_metadata(item):
    metadata = item["metadata"]
    if isinstance(metadata, str):
        metadata = json.loads(metadata)
    return metadata


def lat_lon_mid_pixel(item, subset: str):
    metadata = get_metadata(item)
    if subset == "satellogic":
        crs = metadata["crs"][0]
        bounds_crs = metadata["bounds"]
    elif subset == "neon":
        crs = metadata["epsg"]
        bounds_crs = metadata["bounds"]
    elif subset == "sentinel_1":
        geometry = metadata
    elif subset == "sentinel_2":
        geometry = metadata["tileGeometry"][0]
    else:
        raise ValueError("subset not known")

    if subset.startswith("sentinel_"):
        crs = geometry["crs"]
        bounds_crs = geometry["coordinates"][0]
        assert len(bounds_crs) == 5
        bounds_crs = (
            bounds_crs[0][0],
            bounds_crs[0][1],
            bounds_crs[2][0],
            bounds_crs[2][1],
        )


    bounds = pyproj.Transformer.from_crs(crs, "EPSG:4326").transform_bounds(*bounds_crs)
    # dumb average for now
    return np.array([bounds[0] + bounds[2], bounds[1] + bounds[3]]) / 2


def get_google_map_link(item, subset: str):
    lat, lon = lat_lon_mid_pixel(item, subset)
    return f"https://www.google.com/maps?ll={lat},{lon}&z=16&t=k"