"""
Small helpers for the ICEYE SAR training module.

Data: Sentinel-1 RTC (radiometrically terrain corrected, gamma0, linear power)
and Sentinel-2 L2A, both from Microsoft Planetary Computer's free STAC API.
Only a small window is read from each cloud-optimised GeoTIFF -- nothing is
downloaded whole, nothing is paid for.
"""
import json
import pathlib

import numpy as np
import planetary_computer as pc
import pystac_client
import rasterio
from rasterio.warp import transform_bounds
from rasterio.windows import from_bounds

STAC = "https://planetarycomputer.microsoft.com/api/stac/v1"
HERE = pathlib.Path(__file__).resolve().parent
CACHE = HERE / "cache"
CACHE.mkdir(exist_ok=True)


def catalog():
    return pystac_client.Client.open(STAC, modifier=pc.sign_inplace)


def search(collection, bbox, dt, **query):
    s = catalog().search(collections=[collection], bbox=bbox, datetime=dt,
                         query=query or None)
    items = list(s.items())
    items.sort(key=lambda i: i.properties["datetime"])
    return items


def read_window(href, bbox, out_shape=None):
    """Read bbox (lon/lat) from a COG. Returns (array float32, transform, crs)."""
    with rasterio.open(href) as src:
        b = transform_bounds("EPSG:4326", src.crs, *bbox, densify_pts=21)
        win = from_bounds(*b, transform=src.transform).round_offsets().round_lengths()
        kw = {}
        if out_shape:
            from rasterio.enums import Resampling
            kw["out_shape"] = out_shape
            kw["resampling"] = Resampling.bilinear
        arr = src.read(1, window=win, boundless=True, fill_value=0, **kw).astype("float32")
        tr = src.window_transform(win)
        return arr, tr, src.crs


def s1_db(item, pol, bbox):
    """Sentinel-1 RTC band in dB, cached on disk. Zeros/no-data become NaN."""
    key = f"{item.id}_{pol}_{'_'.join(f'{v:.3f}' for v in bbox)}.npy"
    f = CACHE / key
    if f.exists():
        return np.load(f)
    arr, _, _ = read_window(item.assets[pol].href, bbox)
    arr[arr <= 0] = np.nan
    db = 10 * np.log10(arr)
    np.save(f, db)
    return db


def window_geo(href, bbox):
    """(transform, crs, shape) of the window read_window() would read."""
    with rasterio.open(href) as src:
        b = transform_bounds("EPSG:4326", src.crs, *bbox, densify_pts=21)
        win = from_bounds(*b, transform=src.transform).round_offsets().round_lengths()
        return src.window_transform(win), src.crs, (int(win.height), int(win.width))


def lonlat_to_px(href, bbox, lon, lat):
    from pyproj import Transformer
    tr, crs, _ = window_geo(href, bbox)
    x, y = Transformer.from_crs("EPSG:4326", crs, always_xy=True).transform(lon, lat)
    col, row = ~tr * (x, y)
    return col, row


def read_rgb(href, bbox):
    """3-band (e.g. Sentinel-2 TCI visual) window as uint8 HxWx3."""
    with rasterio.open(href) as src:
        b = transform_bounds("EPSG:4326", src.crs, *bbox, densify_pts=21)
        win = from_bounds(*b, transform=src.transform).round_offsets().round_lengths()
        a = src.read([1, 2, 3], window=win, boundless=True, fill_value=0)
        return np.moveaxis(a, 0, -1)


def to_byte(db, lo, hi):
    x = (np.clip(db, lo, hi) - lo) / (hi - lo)
    x = np.nan_to_num(x, nan=0.0)
    return (x * 255).astype("uint8")


def meta(item):
    p = item.properties
    return {"id": item.id, "datetime": p["datetime"], "orbit": p.get("sat:orbit_state"),
            "relative_orbit": p.get("sat:relative_orbit"), "platform": p.get("platform")}


def save_json(obj, name):
    (HERE / name).write_text(json.dumps(obj, indent=1), encoding="utf-8")
