#!/usr/bin/env python3
"""
Read the SentinelToHeight SAR-LiDAR benchmark (Zarr + GeoParquet).

Install:  pip install xarray zarr geopandas pyarrow matplotlib numpy
Run:      python read_sentineltoheight.py UK_SentinelIcesat2.zarr UK_SentinelIcesat2_lidar.parquet
"""
import sys

import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

zarr_path = sys.argv[1] if len(sys.argv) > 1 else "UK_SentinelIcesat2.zarr"
parquet_path = sys.argv[2] if len(sys.argv) > 2 else "UK_SentinelIcesat2_lidar.parquet"

# 1. Open both files (fast: only the descriptions are read, not the data)
ds = xr.open_zarr(zarr_path)
lidar = gpd.read_parquet(parquet_path)
print(ds)
print(f"\n{ds.sizes['patch']} patches, {len(lidar)} LiDAR footprints")
print(lidar.head())

# 2. Pick one patch (here: the one with the most footprints)
pid = int(lidar["patch_id"].value_counts().idxmax())
p = ds.sel(patch=pid)
I = p["sar_real"].values + 1j * p["sar_imag"].values  # 256 x 256 x 4 complex, as in the .mat file
fp = lidar[lidar["patch_id"] == pid]                   # footprints of this patch
print(f"\nPatch {pid}: file {p['file_name'].values}, master {p['master_date'].values}, "
      f"slave {p['slave_date'].values}, perp. baseline {float(p['perpendicular_baseline']):.1f} m")
print(fp[["pixel_row", "pixel_col", "latitude", "longitude", "rh98", "ground_elevation"]])

# 3. Example query: all patches containing trees taller than 20 m (RH98)
tall = np.sort(lidar.loc[lidar["rh98"] > 20, "patch_id"].unique())
print(f"\n{len(tall)} patches contain footprints with RH98 > 20 m")
subset = ds.sel(patch=tall)  # only these patches are loaded when used

# 4. Show the patch amplitude with its LiDAR footprints (red stars)
fig, axes = plt.subplots(1, 4, figsize=(16, 4))
for c, ax in enumerate(axes):
    ax.imshow(np.abs(I[:, :, c]), cmap="gray", vmax=np.percentile(np.abs(I[:, :, c]), 99))
    ax.scatter(fp["pixel_col"], fp["pixel_row"], c="red", marker="*", s=80)
    ax.set_title(f"Patch {pid}, channel {ds['channel'].values[c]}")
    ax.axis("off")
plt.tight_layout()
plt.show()

# 5. Map of all footprints in the region, coloured by RH98
ax = lidar.plot(column="rh98", cmap="viridis", markersize=5, legend=True, figsize=(6, 8))
ax.set_title("LiDAR footprints, RH98 (m)")
plt.show()
