"""ICEYE open-data helpers: read a GRD COG (radar geometry + RPCs) onto a map grid.

The ICEYE Open Data GRD files carry RPCs, not a map projection. We read either a
decimated overview (whole scene) or a full-resolution window, adjust the RPC
offsets/scales to match what was read, and warp onto a UTM grid at a fixed
height. Data: ICEYE SAR Open Dataset, CC BY 4.0.
"""
import json
import pathlib
import urllib.request

import numpy as np
import rasterio
from rasterio.enums import Resampling
from rasterio.rpc import RPC
from rasterio.warp import reproject
from rasterio.windows import Window

HERE = pathlib.Path(__file__).resolve().parent
CACHE = HERE / "cache"
CACHE.mkdir(exist_ok=True)


def item(stac_url):
    f = CACHE / (stac_url.rsplit("/", 1)[-1])
    if not f.exists():
        with urllib.request.urlopen(stac_url, timeout=60) as r:
            f.write_bytes(r.read())
    return json.loads(f.read_text(encoding="utf-8"))


def grd_meta(it):
    f = CACHE / (it["id"] + "_GRD.json")
    if not f.exists():
        with urllib.request.urlopen(it["assets"]["grd-json"]["href"], timeout=60) as r:
            f.write_bytes(r.read())
    return json.loads(f.read_text(encoding="utf-8"))


def _rpc(d, row0=0.0, col0=0.0, f=1.0):
    """RPC for an image that starts at (row0, col0) of the original and is decimated by f."""
    return RPC(height_off=d["height_off"], height_scale=d["height_scale"],
               lat_off=d["lat_off"], lat_scale=d["lat_scale"],
               long_off=d["long_off"], long_scale=d["long_scale"],
               line_den_coeff=d["line_den_coeff"], line_num_coeff=d["line_num_coeff"],
               samp_den_coeff=d["samp_den_coeff"], samp_num_coeff=d["samp_num_coeff"],
               line_off=(d["line_off"] - row0 + 0.5) / f - 0.5, line_scale=d["line_scale"] / f,
               samp_off=(d["samp_off"] - col0 + 0.5) / f - 0.5, samp_scale=d["samp_scale"] / f)


def read_power(href, row0, col0, h, w, f):
    """Linear power (DN^2) of window (row0, col0, h, w), averaged down by factor f."""
    key = CACHE / f"iceye_{href.rsplit('/', 1)[-1]}_{row0}_{col0}_{h}_{w}_{f}.npy"
    if key.exists():
        return np.load(key)
    with rasterio.open(href) as s:
        a = s.read(1, window=Window(col0, row0, w, h)).astype("float64")
    p = a * a
    if f > 1:
        H, W = (h // f) * f, (w // f) * f
        p = p[:H, :W].reshape(H // f, f, W // f, f).mean(axis=(1, 3))
    p = p.astype("float32")
    np.save(key, p)
    return p


def to_map(power, rpcd, row0, col0, f, dst_transform, dst_crs, dst_shape, height):
    """Warp a power array (read at row0/col0, decimated by f) onto a map grid."""
    out = np.full(dst_shape, np.nan, dtype="float32")
    reproject(power, out, rpcs=_rpc(rpcd, row0, col0, f), src_crs="EPSG:4326",
              dst_transform=dst_transform, dst_crs=dst_crs, resampling=Resampling.bilinear,
              src_nodata=0, dst_nodata=np.nan, RPC_HEIGHT=height)
    return out


def px_on_ground_lonlat(rpcd, H, W, height):
    """Corner lon/lat of the full image at a given height (for choosing a map extent)."""
    from rasterio.transform import RPCTransformer
    with RPCTransformer(_rpc(rpcd), RPC_HEIGHT=height) as t:
        return [t.xy(r, c) for r, c in [(0, 0), (0, W), (H, 0), (H, W)]]


def latlon_to_px(rpcd, lon, lat, height):
    from rasterio.transform import RPCTransformer
    with RPCTransformer(_rpc(rpcd), RPC_HEIGHT=height) as t:
        r, c = t.rowcol(lon, lat)
    return int(r), int(c)
