#!/usr/bin/env python3
"""
Convert the SentinelToHeight pixel summary (one row per SAR pixel with a LiDAR value)
from MATLAB (.mat, saved with -struct) to a Zarr store.

Run:
    python summary2zarr.py SentinelToHeight_summary.mat --out SentinelToHeight_summary.zarr
"""
import argparse

import numpy as np
import pandas as pd
import xarray as xr

# MATLAB name -> (new name, units, description)
VARS = {
    "C11": ("C11", "1", "Covariance matrix element C11 (4x4 PolInSAR covariance)"),
    "C12": ("C12", "1", "Covariance matrix element C12 (4x4 PolInSAR covariance)"),
    "C13": ("C13", "1", "Covariance matrix element C13 (4x4 PolInSAR covariance)"),
    "C14": ("C14", "1", "Covariance matrix element C14 (4x4 PolInSAR covariance)"),
    "C22": ("C22", "1", "Covariance matrix element C22 (4x4 PolInSAR covariance)"),
    "C23": ("C23", "1", "Covariance matrix element C23 (4x4 PolInSAR covariance)"),
    "C24": ("C24", "1", "Covariance matrix element C24 (4x4 PolInSAR covariance)"),
    "C33": ("C33", "1", "Covariance matrix element C33 (4x4 PolInSAR covariance)"),
    "C34": ("C34", "1", "Covariance matrix element C34 (4x4 PolInSAR covariance)"),
    "C44": ("C44", "1", "Covariance matrix element C44 (4x4 PolInSAR covariance)"),
    "Latitude": ("latitude", "degrees_north", "Latitude of the SAR pixel"),
    "Longitude": ("longitude", "degrees_east", "Longitude of the SAR pixel"),
    "RH98": ("rh98", "m", "LiDAR forest height RH98"),
    "DTM": ("dtm", "m", "Terrain elevation (DTM) at the pixel"),  # TODO: say which DTM source
    "LidarSource": ("lidar_source", None, "LiDAR sensor (GEDI or ICESat-2)"),
    "Range": ("slant_range", "m", "Slant range of the SAR pixel"),
    "bn": ("perpendicular_baseline", "m", "Perpendicular baseline at the pixel"),
    "kz": ("kz", "rad m-1", "Vertical wavenumber at the pixel"),
    "theta": ("look_angle", None, "Look angle of the master pixel"),  # units set below
    "mst_date": ("master_date", None, "Sentinel-1 master acquisition date"),
    "slv_date": ("slave_date", None, "Sentinel-1 slave acquisition date"),
}


def load(path):
    """Read a -struct .mat file (v7.3 via mat73, older versions via scipy)."""
    try:
        import scipy.io
        d = scipy.io.loadmat(path, squeeze_me=True)
        return {k: v for k, v in d.items() if not k.startswith("__")}
    except NotImplementedError:
        import mat73
        return mat73.loadmat(path)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("mat_file")
    ap.add_argument("--out", default="SentinelToHeight_summary.zarr")
    ap.add_argument("--chunk", type=int, default=1_000_000, help="Rows per chunk")
    args = ap.parse_args()

    print(f"Reading {args.mat_file} ...")
    d = load(args.mat_file)
    n = len(np.ravel(d["Latitude"]))
    print(f"  {n} pixels, fields: {sorted(d)}")

    data_vars = {}
    for mat_name, (name, units, desc) in VARS.items():
        if mat_name not in d:
            print(f"  WARNING: {mat_name} not found, skipped")
            continue
        v = d[mat_name]
        attrs = {"long_name": desc}

        if mat_name in ("mst_date", "slv_date"):  # yyyymmdd integers -> dates
            v = pd.to_datetime(np.ravel(v).astype(int).astype(str), format="%Y%m%d").to_numpy()
        elif mat_name == "LidarSource":  # code from MATLAB: 1 = GEDI, 2 = ICESat-2
            codes = np.ravel(np.asarray(v)).astype(int)
            v = np.where(codes == 1, "GEDI", np.where(codes == 2, "ICESat-2", "unknown")).astype("U10")
            print(f"  LiDAR source counts: {dict(zip(*np.unique(v, return_counts=True)))}")
        else:
            v = np.ravel(np.asarray(v))
            if mat_name == "theta":
                units = "rad" if np.nanmax(np.abs(v)) < 3.2 else "degree"
        if units:
            attrs["units"] = units

        if np.iscomplexobj(v):  # Parquet/Zarr tools handle real numbers best
            data_vars[name + "_real"] = ("point", v.real, {**attrs, "long_name": desc + ", real part"})
            data_vars[name + "_imag"] = ("point", v.imag, {**attrs, "long_name": desc + ", imaginary part"})
        else:
            data_vars[name] = ("point", v, attrs)

    ds = xr.Dataset(data_vars, coords={"point": np.arange(n, dtype=np.int64)})
    ds["point"].attrs["long_name"] = "Pixel index (one SAR pixel with a co-located LiDAR measurement)"
    ds.attrs.update({
        "title": "SentinelToHeight SAR-LiDAR pixel summary",
        "summary": "One row per Sentinel-1 pixel with a co-located GEDI or ICESat-2 measurement: "
                   "4x4 PolInSAR covariance elements, geometry, baseline, dates and LiDAR RH98.",
        "project": "SentinelToHeight (ESA)",
        "institution": "University of Twente, Faculty ITC",
        "references": "https://www.sentinel2height.nl/",
        "license": "TODO: e.g. CC-BY-4.0",
        "Conventions": "CF-1.8",
    })

    enc = {v: {"chunks": (min(args.chunk, n),)} for v in ds.data_vars}
    try:
        ds.to_zarr(args.out, mode="w", encoding=enc, consolidated=True, zarr_format=2)
    except TypeError:  # older xarray
        ds.to_zarr(args.out, mode="w", encoding=enc, consolidated=True)
    print(f"Saved {args.out}")

    # Check: re-open and compare with the original
    back = xr.open_zarr(args.out)
    ok = True
    for mat_name, (name, _, _) in VARS.items():
        if mat_name in d and name in back and mat_name not in ("mst_date", "slv_date", "LidarSource"):
            ok &= np.array_equal(np.ravel(d[mat_name]), back[name].values, equal_nan=True)
    print("Verification:", "all identical" if ok else "PROBLEM FOUND")
    print(back)


if __name__ == "__main__":
    main()
