#!/usr/bin/env python3
"""
Show one patch: SAR image (4 channels), geometry layers, and where each LiDAR point sits.

Run:
    python show_patch.py UK_SentinelIcesat2.zarr UK_SentinelIcesat2_lidar.parquet          # patch with most footprints
    python show_patch.py UK_SentinelIcesat2.zarr UK_SentinelIcesat2_lidar.parquet 57       # a chosen patch
"""
import sys

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

zarr_path, parquet_path = sys.argv[1], sys.argv[2]

# ---- open the data ------------------------------------------------------
ds = xr.open_zarr(zarr_path)
lidar = gpd.read_parquet(parquet_path)

# ---- choose the patch ---------------------------------------------------
if len(sys.argv) > 3:
    pid = int(sys.argv[3])
else:
    pid = int(lidar["patch_id"].value_counts().idxmax())  # the patch with most LiDAR points

p = ds.sel(patch=pid)                                   # this patch (from the Zarr)
I = p["sar_real"].values + 1j * p["sar_imag"].values    # SAR data, 256 x 256 x 4 complex
fp = lidar[lidar["patch_id"] == pid].reset_index(drop=True)  # its LiDAR points

# ---- print patch information and LiDAR points ---------------------------
print(f"\nPatch {pid}")
print(f"  file:          {p['file_name'].values}")
print(f"  master/slave:  {str(p['master_date'].values)[:10]} / {str(p['slave_date'].values)[:10]}")
print(f"  perp baseline: {float(p['perpendicular_baseline']):.2f} m")
print(f"  height of amb: {float(p['height_of_ambiguity']):.2f} m")
print(f"  coherence:     {float(p['modelled_coherence']):.3f}")
print(f"\n  {len(fp)} LiDAR point(s):")
cols = [c for c in ["pixel_row", "pixel_col", "latitude", "longitude", "rh98", "rh100", "ground_elevation"]
        if c in fp.columns]
print(fp[cols].to_string(index=True))

# ---- figure -------------------------------------------------------------
def add_points(ax, numbers=False):
    """Draw the LiDAR points on an image (x = column, y = row)."""
    ax.scatter(fp["pixel_col"], fp["pixel_row"], c="red", marker="*", s=90, edgecolors="white", linewidths=0.5)
    if numbers:
        for k, r in fp.iterrows():
            ax.annotate(f"{k}: RH98={r['rh98']:.1f} m\n(row {r['pixel_row']}, col {r['pixel_col']})",
                        (r["pixel_col"], r["pixel_row"]), xytext=(6, 6), textcoords="offset points",
                        color="yellow", fontsize=8,
                        bbox=dict(facecolor="black", alpha=0.6, pad=1, edgecolor="none"))

fig, axes = plt.subplots(3, 4, figsize=(18, 13))
fig.suptitle(f"Patch {pid}  |  {p['file_name'].values}  |  {len(fp)} LiDAR point(s)", fontsize=13)

# Row 1: SAR amplitude of the 4 channels
channels = ds["channel"].values
for c in range(4):
    amp = np.abs(I[:, :, c])
    ax = axes[0, c]
    ax.imshow(amp, cmap="gray", vmin=0, vmax=np.nanpercentile(amp, 99))
    add_points(ax)
    ax.set_title(f"SAR amplitude, channel {channels[c]}")

# Row 2: geometry layers
geometry = [("incidence_angle", "Incidence angle (deg)"), ("slant_range", "Slant range (m)"),
            ("latitude", "Latitude (deg)"), ("longitude", "Longitude (deg)")]
for c, (name, title) in enumerate(geometry):
    ax = axes[1, c]
    im = ax.imshow(p[name].values, cmap="viridis")
    add_points(ax)
    ax.set_title(title)
    fig.colorbar(im, ax=ax, fraction=0.046)

# Row 3: SAR with numbered LiDAR points, and the LiDAR RH98 map itself
for c in range(4):
    axes[2, c].remove()
big = fig.add_subplot(3, 2, 5)
amp = np.abs(I[:, :, 0])
big.imshow(amp, cmap="gray", vmin=0, vmax=np.nanpercentile(amp, 99))
add_points(big, numbers=True)
big.set_title("LiDAR points on SAR (channel 1): number, RH98 and pixel position")

rhmap = p["lidar_rh98"].values.astype(float)
rhmap[rhmap == 0] = np.nan                                 # empty pixels -> transparent
mapax = fig.add_subplot(3, 2, 6)
mapax.imshow(amp, cmap="gray", vmin=0, vmax=np.nanpercentile(amp, 99), alpha=0.4)
im = mapax.imshow(rhmap, cmap="viridis", interpolation="nearest")
rr, cc = np.nonzero(np.isfinite(rhmap))
mapax.scatter(cc, rr, s=200, facecolors="none", edgecolors="red")  # circle the tiny pixels
mapax.set_title("Original LiDAR RH98 map from the .mat (values only at footprint pixels)")
fig.colorbar(im, ax=mapax, fraction=0.046, label="RH98 (m)")

plt.tight_layout()
out = f"patch_{pid}.png"
plt.savefig(out, dpi=120)
print(f"\nFigure saved as {out}")
plt.show()
