"""Tutorial 10 — BRDF Simulation

Main plane BRF scan of corn field with observation zenith angle from -60° to +60°."""

import less
import numpy as np

# ──Constructing the scene───────────────────────────────────────────────
scene = less.Scene()
scene.size = 10.0
scene.repetitive = False

scene.terrain = less.Terrain(property=less.Lambertian(reflectance=0.15))
scene.illumination = less.Illumination(source=less.Sun(zenith=30, azimuth=180), atmosphere=less.NoAtmosphere())

maize = less.Object("maize", mesh=less.examples.asset_path("maize.obj"))
maize.set_property(less.Prospect(cab=45, car=10, cw=0.012, cm=0.006, N=1.55))

rng = np.random.RandomState(42)
positions = less.place.grid(scene, spacing=0.75, jitter=0.04)
n = len(positions)
scene.add(maize, positions=positions,
          scales=rng.uniform(0.9, 1.1, n),
          rotations=rng.uniform(0, 360, n))
view_zeniths = np.arange(-60, 65, 5)
brf_red = []
brf_nir = []

for vza in view_zeniths:
    if vza < 0:
        view_az = 180  # backscatter
    elif vza > 0:
        view_az = 0    # forward scatter
    else:
        view_az = 0    # substar point

    sensor = less.OpticalImager(
        less.Orthographic(image_size=128, view_zenith=abs(vza), view_azimuth=view_az),
        bands=[650, 850], quality=512,
    )
    image = scene.simulate(sensor)
    data = image.data
    brf_red.append(np.mean(data[:, :, 0]))
    brf_nir.append(np.mean(data[:, :, 1]))

brf_red = np.array(brf_red)
brf_nir = np.array(brf_nir)

# ── Print results ─────────────────────────────────────────────
print("Main plane BRF (SZA=30°, SAA=180°)")
print(f"{'VZA':>6s}  {'Red(650)':>10s}  {'NIR(850)':>10s}")
for vza, r, ni in zip(view_zeniths, brf_red, brf_nir):
    marker = " ← hot spot" if abs(vza - (-30)) < 3 else ""
    print(f"{vza:>6d}  {r:>10.4f}  {ni:>10.4f}{marker}")

# ── Visualization (if matplotlib is available)────────────────────────────
try:
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(view_zeniths, brf_red, 'r-o', label='Red (650 nm)', markersize=4)
    ax.plot(view_zeniths, brf_nir, 'b-s', label='NIR (850 nm)', markersize=4)
    ax.axvline(-30, color='orange', linestyle='--', alpha=0.5, label='Hot spot (VZA=SZA)')
    ax.axvline(0, color='gray', linestyle=':', alpha=0.3)
    ax.set_xlabel('View Zenith Angle (°)\n← Backscatter | Forward scatter →')
    ax.set_ylabel('BRF')
    ax.set_title('Principal Plane BRF (SZA=30°, SAA=180°)')
    ax.legend()
    ax.grid(True, alpha=0.3)
    plt.savefig("10_brf_principal_plane.png", dpi=150, bbox_inches='tight')
    print("Chart saved: 10_brf_principal_plane.png")
except ImportError:
    print("matplotlib is not available, skip visualization")

print("Tutorial 10 completed!")
