# ruff: noqa: E501, RUF003
"""Prototype measurements for the GeoStack SAR geocoding design (NumPy, float64).

Each block prints one group of rows of the design's numerics table (section 5).
Every setting comes from `configs/sar_geocoding.yaml`. Given a path, it also writes those numbers there as a flat JSON dict of scalars:
the `sar_geocoding_prototype` stage of `dvc.yaml` writes
`results/metrics/sar_geocoding.json` this way.
Everything is synthetic: a circular sun-synchronous orbit seen from a rotating
WGS84 Earth, sampled every 10 s as Sentinel-1 annotations are, and a Gaussian
hill seen in the zero-Doppler plane. Nothing is downloaded.
"""

import json
import sys
from pathlib import Path

import numpy as np
import yaml


CFG = yaml.safe_load(
    (Path(__file__).resolve().parents[3] / "configs" / "sar_geocoding.yaml").read_text()
)


METRICS = {}


def record(**values):
    """Keep the numbers a printed row shows, rounded as it shows them."""
    METRICS.update(values)


# --- WGS84 and the orbit -----------------------------------------------------

A = 6378137.0
F = 1.0 / 298.257223563
B = A * (1.0 - F)
E2 = 1.0 - (B / A) ** 2
OMEGA_E = 7.2921150e-5
GM = 3.986004418e14

RADIUS = A + CFG["orbit"]["altitude_m"]
INCLINATION = np.deg2rad(CFG["orbit"]["inclination_deg"])
NODE = np.deg2rad(CFG["orbit"]["node_deg"])
MEAN_MOTION = np.sqrt(GM / RADIUS**3)
SPACING = CFG["orbit"]["spacing_s"]
NODES = np.arange(CFG["orbit"]["n_state_vectors"]) * SPACING


def orbit(t):
    """ECEF position (m), velocity (m/s) and acceleration of the true orbit at t."""
    t = np.atleast_1d(t)
    u = 0.3 + MEAN_MOTION * t
    cu, su = np.cos(u), np.sin(u)
    ci, si = np.cos(INCLINATION), np.sin(INCLINATION)
    cn, sn = np.cos(NODE), np.sin(NODE)
    p_hat = np.stack([cu * cn - su * ci * sn, cu * sn + su * ci * cn, su * si], -1)
    q_hat = np.stack([-su * cn - cu * ci * sn, -su * sn + cu * ci * cn, cu * si], -1)
    r_eci = RADIUS * p_hat
    v_eci = RADIUS * MEAN_MOTION * q_hat
    a_eci = -(MEAN_MOTION**2) * r_eci
    theta = OMEGA_E * t
    c, s = np.cos(theta), np.sin(theta)

    def rot(x):
        # R_z(−θ) x: inertial to Earth-fixed
        return np.stack(
            [c * x[:, 0] + s * x[:, 1], -s * x[:, 0] + c * x[:, 1], x[:, 2]], -1
        )

    def cross_w(x):
        # ω × x with ω = ω_E ẑ
        return OMEGA_E * np.stack([-x[:, 1], x[:, 0], np.zeros_like(x[:, 0])], -1)

    r = rot(r_eci)
    v = rot(v_eci) - cross_w(r)
    a = rot(a_eci) - 2 * cross_w(v) - cross_w(cross_w(r))
    return r, v, a


def hermite(t, nodes, pos, vel):
    """Cubic Hermite position, velocity and acceleration from state vectors."""
    t = np.atleast_1d(t)
    i = np.clip(np.searchsorted(nodes, t) - 1, 0, len(nodes) - 2)
    h = nodes[i + 1] - nodes[i]
    s = ((t - nodes[i]) / h)[:, None]
    hh = h[:, None]
    p0, p1, m0, m1 = pos[i], pos[i + 1], hh * vel[i], hh * vel[i + 1]
    position = (
        (2 * s**3 - 3 * s**2 + 1) * p0
        + (s**3 - 2 * s**2 + s) * m0
        + (-2 * s**3 + 3 * s**2) * p1
        + (s**3 - s**2) * m1
    )
    velocity = (
        (6 * s**2 - 6 * s) * p0
        + (3 * s**2 - 4 * s + 1) * m0
        + (-6 * s**2 + 6 * s) * p1
        + (3 * s**2 - 2 * s) * m1
    ) / hh
    accel = (
        (12 * s - 6) * p0 + (6 * s - 4) * m0 + (-12 * s + 6) * p1 + (6 * s - 2) * m1
    ) / hh**2
    return position, velocity, accel


def lagrange(t, nodes, values, order=CFG["orbit"]["lagrange_order"]):
    """Lagrange interpolation of `values` on the `order` nodes around each t."""
    t = np.atleast_1d(t)
    out = np.empty((len(t), values.shape[1]))
    for k, tk in enumerate(t):
        centre = np.searchsorted(nodes, tk)
        lo = int(np.clip(centre - order // 2, 0, len(nodes) - order))
        idx = np.arange(lo, lo + order)
        weights = np.ones(order)
        for j in range(order):
            for m in range(order):
                if m != j:
                    weights[j] *= (tk - nodes[idx[m]]) / (nodes[idx[j]] - nodes[idx[m]])
        out[k] = weights @ values[idx]
    return out


pos_nodes, vel_nodes, _ = orbit(NODES)
dense = np.linspace(NODES[0], NODES[-1], CFG["orbit"]["dense_samples"])
true_r, true_v, _ = orbit(dense)
margin = CFG["orbit"]["inner_margin"]
inner = (dense >= NODES[margin]) & (dense <= NODES[-1 - margin])

print(
    f"== Orbit interpolation (max error over the inner {NODES[-1 - margin] - NODES[margin]:.0f} s; {SPACING:.0f} s spacing)"
)
i = np.clip(np.searchsorted(NODES, dense) - 1, 0, len(NODES) - 2)
w = ((dense - NODES[i]) / SPACING)[:, None]
chord = (1 - w) * pos_nodes[i] + w * pos_nodes[i + 1]
chord_err = np.linalg.norm(chord - true_r, axis=1)[inner].max()
print(f"chord position error: {chord_err:.3g} m")
h_r, h_v, _ = hermite(dense, NODES, pos_nodes, vel_nodes)
h_r_err = np.linalg.norm(h_r - true_r, axis=1)[inner].max()
h_v_err = np.linalg.norm(h_v - true_v, axis=1)[inner].max()
print(f"hermite position error: {h_r_err:.3g} m")
print(f"hermite velocity error: {h_v_err:.3g} m/s")
l_r = lagrange(dense, NODES, pos_nodes)
l_v = lagrange(dense, NODES, vel_nodes)
# Lagrange's errors are float64 round-off, which differs between platforms
# (4.6 nm on Linux, 4.8 nm on macOS), so the row states the bound they sit below.
l_r_err = np.linalg.norm(l_r - true_r, axis=1)[inner].max()
l_v_err = np.linalg.norm(l_v - true_v, axis=1)[inner].max()
assert l_r_err < 1e-8
assert l_v_err < 1e-10
print("lagrange8 position error: below 1e-08 m (round-off)")
print("lagrange8 velocity error: below 1e-10 m/s (round-off)")
record(
    chord_position_error_m=float(f"{chord_err:.3g}"),
    hermite_position_error_m=float(f"{h_r_err:.3g}"),
    hermite_velocity_error_m_s=float(f"{h_v_err:.2g}"),
    lagrange8_position_error_below_m=1e-8,
    lagrange8_velocity_error_below_m_s=1e-10,
)


# --- targets on the ground ----------------------------------------------------


def geodetic_normal(p):
    n = p / np.array([A**2, A**2, B**2])
    return n / np.linalg.norm(n, axis=-1, keepdims=True)


def ray_ellipsoid(origin, direction):
    """First intersection of origin + s·direction with the WGS84 ellipsoid."""
    scale = np.array([A, A, B])
    o, d = origin / scale, direction / scale
    qa = np.sum(d * d, -1)
    qb = 2 * np.sum(o * d, -1)
    qc = np.sum(o * o, -1) - 1
    s = (-qb - np.sqrt(qb**2 - 4 * qa * qc)) / (2 * qa)
    return origin + s[..., None] * direction


def target(t_az, look_deg):
    """A point on the ellipsoid seen at zero Doppler at t_az, right-looking."""
    r, v, _ = orbit(t_az)
    r, v = r[0], v[0]
    down = -r / np.linalg.norm(r)
    along = v / np.linalg.norm(v)
    down = down - (down @ along) * along
    down /= np.linalg.norm(down)
    right = np.cross(along, down)
    look = np.deg2rad(look_deg)
    direction = np.cos(look) * down + np.sin(look) * right
    p = ray_ellipsoid(r, direction)
    incidence = np.degrees(
        np.arccos(geodetic_normal(p) @ (r - p) / np.linalg.norm(r - p))
    )
    return p, incidence


def doppler(t, p):
    s, v, a = hermite(t, NODES, pos_nodes, vel_nodes)
    d = np.sum((s - p) * v, -1)
    d_exact = np.sum(v * v, -1) + np.sum((s - p) * a, -1)
    d_approx = np.sum(v * v, -1)
    return d, d_exact, d_approx


TOL = CFG["zero_doppler"]["tolerance_s"]


def newton(p, derivative, tol=TOL, t0=None, max_iter=50):
    t = np.array([NODES[len(NODES) // 2] if t0 is None else t0])
    for k in range(1, max_iter + 1):
        d, d_exact, d_approx = doppler(t, p)
        step = d / (d_exact if derivative == "exact" else d_approx)
        t = t - step
        if abs(step[0]) < tol:
            return t[0], k
    return t[0], max_iter


def bisection(p, tol=TOL):
    lo, hi = NODES[0], NODES[-1]
    f_lo = doppler(np.array([lo]), p)[0][0]
    k = 0
    while hi - lo > tol:
        mid = 0.5 * (lo + hi)
        f_mid = doppler(np.array([mid]), p)[0][0]
        if np.sign(f_mid) == np.sign(f_lo):
            lo, f_lo = mid, f_mid
        else:
            hi = mid
        k += 1
    return 0.5 * (lo + hi), k


print(f"== Zero-Doppler solve (tolerance {TOL:g} s, start at the table's middle)")
zd = CFG["zero_doppler"]
targets = [
    target(t, look) for t in zd["azimuth_times_s"] for look in zd["look_angles_deg"]
]
incidences = [inc for _, inc in targets]
print(f"incidence range of targets: {min(incidences):.1f} to {max(incidences):.1f} deg")
results = {"exact": [], "approx": [], "bisection": []}
for p, _ in targets:
    results["exact"].append(newton(p, "exact"))
    results["approx"].append(newton(p, "approx"))
    results["bisection"].append(bisection(p))
for name in results:
    iters = [k for _, k in results[name]]
    print(f"{name} iterations: {min(iters)} to {max(iters)}")
    record(
        **{f"{name}_iterations_min": min(iters), f"{name}_iterations_max": max(iters)}
    )
gap = max(
    abs(a[0] - b[0])
    for a, b in zip(results["exact"], results["bisection"], strict=True)
)
print(f"max |t_newton - t_bisection|: {gap:.2g} s")
record(max_newton_bisection_gap_s=float(f"{gap:.2g}"))


print("== Sensitivities at zero Doppler")
sens = CFG["sensitivity"]
dh = sens["height_error_m"]
for look in sens["look_angles_deg"]:
    p, inc = target(sens["azimuth_time_s"], look)
    n_hat = geodetic_normal(p)
    t0, _ = newton(p, "exact")
    s0 = hermite(np.array([t0]), NODES, pos_nodes, vel_nodes)[0][0]
    r0 = np.linalg.norm(s0 - p)
    p_up = p + dh * n_hat
    t1, _ = newton(p_up, "exact")
    s1 = hermite(np.array([t1]), NODES, pos_nodes, vel_nodes)[0][0]
    r1 = np.linalg.norm(s1 - p_up)
    shift = (r0 - r1) / np.sin(np.deg2rad(inc))
    print(
        f"{dh:.0f} m height error at incidence {inc:.1f} deg: slant {r0 - r1:.1f} m, ground {shift:.1f} m = {shift / sens['grd_pixel_m']:.1f} GRD pixels; azimuth {abs(t1 - t0) * 1e3:.3f} ms"
    )
    key = f"incidence_{inc:.1f}".replace(".", "p")
    record(
        **{
            f"{key}_slant_shift_m": round(r0 - r1, 1),
            f"{key}_ground_shift_m": round(shift, 1),
            f"{key}_azimuth_shift_ms": round(abs(t1 - t0) * 1e3, 3),
        }
    )

p, _ = target(sens["azimuth_time_s"], sens["derivative_look_deg"])
n_hat = geodetic_normal(p)
t0, _ = newton(p, "exact")
s0, v0, a0 = (x[0] for x in hermite(np.array([t0]), NODES, pos_nodes, vel_nodes))
r0 = np.linalg.norm(s0 - p)
# implicit function theorem: ∂t/∂h = −(∂D/∂P · n̂)/(∂D/∂t) = (V · n̂)/D'(t); ∂r/∂h = −(S − P)/r · n̂ (∂r/∂t = 0)
dt_dh = (v0 @ n_hat) / (v0 @ v0 + (s0 - p) @ a0)
dr_dh = -((s0 - p) / r0) @ n_hat
step = sens["derivative_step_m"]
fd_tol = sens["derivative_tolerance_s"]
t_plus, _ = newton(p + step * n_hat, "exact", tol=fd_tol)
t_minus, _ = newton(p - step * n_hat, "exact", tol=fd_tol)
fd_dt = (t_plus - t_minus) / (2 * step)


def range_at(point, t):
    return np.linalg.norm(
        hermite(np.array([t]), NODES, pos_nodes, vel_nodes)[0][0] - point
    )


fd_dr = (range_at(p + step * n_hat, t_plus) - range_at(p - step * n_hat, t_minus)) / (
    2 * step
)
print(
    f"dr/dh implicit {dr_dh:.6f}, finite difference {fd_dr:.6f}, relative gap {abs(dr_dh - fd_dr) / abs(fd_dr):.1g}"
)
print(f"dt/dh implicit {dt_dh:.4g} s/m, finite difference {fd_dt:.4g} s/m")
record(
    dr_dh=round(dr_dh, 6),
    dr_dh_relative_gap=float(f"{abs(dr_dh - fd_dr) / abs(fd_dr):.1g}"),
    dt_dh_s_m=float(f"{dt_dh:.4g}"),
)


# --- layover, shadow and the radiometry of a hill ------------------------------
# One range line in the zero-Doppler plane, locally flat Earth: the sensor at
# height H, the ground at horizontal distance x from nadir, terrain z(x).

print("== Layover and shadow on a Gaussian hill (one range line)")
H = CFG["orbit"]["altitude_m"]
ds = CFG["hill"]["profile_step_m"]
half = CFG["hill"]["profile_half_width_m"]
x = np.arange(-half, half, ds)


def hill_line(height, width, incidence_deg):
    x0 = H * np.tan(np.deg2rad(incidence_deg))
    z = height * np.exp(-0.5 * (x / width) ** 2)
    gx = x0 + x
    slant = np.hypot(gx, H - z)
    look = np.arctan2(gx, H - z)
    return gx, z, slant, look


for height, width, incidence in CFG["hill"]["cases"]:
    gx, z, slant, look = hill_line(height, width, incidence)
    hill = z > 1.0
    dr = np.gradient(slant, ds)
    active = dr <= 0
    # passive layover: a point whose slant range is shared with an active-layover point
    if active.any():
        lo, hi = slant[active].min(), slant[active].max()
        passive = (slant >= lo) & (slant <= hi) & ~active
    else:
        passive = np.zeros_like(active)
    shadow = look < np.maximum.accumulate(look) - 1e-12
    slope = np.gradient(z, ds)
    # active layover from the local rule: foreslope steeper than the look angle
    rule = np.arctan(slope) >= look
    agree = np.mean(rule[hill] == active[hill])
    print(
        f"hill {height:.0f} m, width {width:.0f} m, incidence {incidence:.0f} deg: "
        f"active layover {100 * active[hill].mean():.1f}%, passive {100 * passive[hill].mean():.1f}%, "
        f"shadow {100 * shadow[hill].mean():.1f}% of hill cells; slope rule agrees on {100 * agree:.1f}%"
    )
    key = f"hill_{height:.0f}_{width:.0f}_{incidence:.0f}"
    record(
        **{
            f"{key}_active_layover_pct": round(100 * active[hill].mean(), 1),
            f"{key}_passive_layover_pct": round(100 * passive[hill].mean(), 1),
            f"{key}_shadow_pct": round(100 * shadow[hill].mean(), 1),
            f"{key}_slope_rule_agrees_pct": round(100 * agree, 1),
        }
    )

print("== Ellipsoid gamma0 on a hill (true gamma0 = 1 everywhere, area model)")
# a finer profile, so each slant bin holds many facets and the
# quantisation of facets into bins stays small
gam = CFG["gamma"]
ds_fine = gam["profile_step_m"]
x = np.arange(-gam["profile_half_width_m"], gam["profile_half_width_m"], ds_fine)
gx, z, slant, look = hill_line(*gam["hill"])
dz = np.gradient(z, ds_fine)
normal = np.stack([-dz, np.ones_like(dz)], -1) / np.hypot(dz, 1)[:, None]
to_sensor = np.stack([-gx, H - z], -1) / slant[:, None]
facet = ds_fine * np.hypot(dz, 1)
visible = look >= np.maximum.accumulate(look) - 1e-12
# A_γ: a facet's area projected onto the plane normal to the look direction
cos_local = np.einsum("ij,ij->i", normal, to_sensor)
area_gamma = np.where(visible & (cos_local > 0), facet * cos_local, 0.0)
bin_size = gam["slant_bin_m"]
bins = np.floor((slant - slant.min()) / bin_size).astype(int)
counts = np.bincount(bins)
power = np.bincount(bins, weights=area_gamma)
beta0 = power / bin_size
# radiomax today: γ⁰ = β⁰ tan θ_ell, with θ_ell the incidence on flat ground at this range
centre_range = slant.min() + (np.arange(len(beta0)) + 0.5) * bin_size
theta_ell = np.arccos(np.clip(H / centre_range, -1, 1))
gamma_ell = beta0 * np.tan(theta_ell)
# a flat bin: every facet in it is flat, and it is not a partial bin at either end
flat = (np.bincount(bins, weights=np.abs(dz) < 1e-3) == counts) & (counts > 0)
flat[[0, -1]] = False
layover_bins = np.bincount(bins, weights=np.gradient(slant, ds_fine) <= 0) > 0
populated = beta0 > 0
flat_err = np.abs(10 * np.log10(gamma_ell[flat]))
slope_db = 10 * np.log10(gamma_ell[populated & ~flat & ~layover_bins])
layover_db = 10 * np.log10(gamma_ell[populated & layover_bins])
print(f"flat bins: max |error| {flat_err.max():.2f} dB")
print(
    f"slope bins outside layover: ellipsoid gamma0 from {slope_db.min():.1f} to {slope_db.max():.1f} dB (truth 0 dB)"
)
print(
    f"layover bins: ellipsoid gamma0 from {layover_db.min():.1f} to {layover_db.max():.1f} dB (truth 0 dB)"
)
record(
    flat_bins_max_error_db=round(flat_err.max(), 2),
    slope_bins_min_db=round(slope_db.min(), 1),
    slope_bins_max_db=round(slope_db.max(), 1),
    layover_bins_min_db=round(layover_db.min(), 1),
    layover_bins_max_db=round(layover_db.max(), 1),
)

if len(sys.argv) > 1:
    out = Path(sys.argv[1])
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(
        json.dumps({k: float(v) for k, v in METRICS.items()}, indent=2) + "\n"
    )
