"""Check candidate annotation points on 04_geometry.png against the DEM: for a point in panel B/C (ascending,
radar looks east) or D (descending, looks west), report the share of nearby pixels in geometric layover
(slope facing the radar steeper than the incidence angle) or shadow (slope facing away steeper than 90 - incidence),
plus the RTC dB. Range slope only (east-west), incidence taken as 37 deg: a rough, honest test.
usage: python check_geometry_points.py C:x,y D:x,y ..."""
import pathlib
import sys

import numpy as np
from PIL import Image

sys.path.insert(0, str(pathlib.Path(__file__).parent))
from build_figures import GEO_BB
from sarlib import read_window, s1_db, search

bb = GEO_BB
items = search("sentinel-1-rtc", bb, "2026-11-01/2026-11-21")
asc = [i for i in items if i.properties["sat:orbit_state"] == "ascending"][-1]
dsc = [i for i in items if i.properties["sat:orbit_state"] == "descending"][-1]
a, d = s1_db(asc, "vv", bb), s1_db(dsc, "vv", bb)
dem_item = search("cop-dem-glo-30", bb, None)[0]
dem, _, _ = read_window(dem_item.assets["data"].href, bb, out_shape=a.shape)
gy, gx = np.gradient(dem, 10.0)
rng = np.degrees(np.arctan(gx))  # + = ground rises towards the east
TH = 37.0

fig = np.asarray(Image.open(pathlib.Path(__file__).resolve().parent.parent / "img" / "04_geometry.png").convert("L"))


def extent(x_lo, x_hi, y_lo, y_hi):
    """Bounds of the non-white image block inside a rough panel region."""
    sub = fig[y_lo:y_hi, x_lo:x_hi] < 245
    cols = np.where(sub.mean(0) > 0.6)[0]; rows = np.where(sub.mean(1) > 0.6)[0]
    return x_lo + cols[0], x_lo + cols[-1], y_lo + rows[0], y_lo + rows[-1]


PAN = {"B": extent(900, 1790, 160, 830), "C": extent(20, 890, 860, 1540), "D": extent(900, 1790, 860, 1540)}
print("panels", PAN, "array", a.shape)
for arg in sys.argv[1:]:
    p, xy = arg.split(":")
    x, y = (int(v) for v in xy.split(","))
    x0, x1, y0, y1 = PAN[p]
    c = int((x - x0) / (x1 - x0) * a.shape[1]); r = int((y - y0) / (y1 - y0) * a.shape[0])
    w = rng[max(0, r - 8):r + 8, max(0, c - 8):c + 8]
    if p in "BC":   # radar to the west: a slope facing it rises towards the east
        lay, sha, img = (w > TH).mean(), (w < -(90 - TH)).mean(), a
    else:           # radar to the east
        lay, sha, img = (w < -TH).mean(), (w > (90 - TH)).mean(), d
    facing = (w > 15).mean() if p in "BC" else (w < -15).mean()
    away = (w < -15).mean() if p in "BC" else (w > 15).mean()
    print(f"{arg:12s} dB={np.nanmedian(img[max(0,r-4):r+4, max(0,c-4):c+4]):6.1f}  facing-radar(>15deg)={facing:4.0%}  "
          f"facing-away={away:4.0%}  layover={lay:4.0%}  shadow={sha:4.0%}")
