import os
from pathlib import Path

# --8<-- [start:code]
"""Binary dielectric grating: where the diffraction orders go, with ``jno.rcwa``.

A plane wave at normal incidence hits a periodic slab, a high-index ridge filling half of each cell. Order m
propagates when |m λ/Λ| ≤ 1 (the grating equation); sweeping the period Λ through λ switches the ±1 orders
on, the Rayleigh anomaly. The problem is the scalar-Helmholtz term list ``jno.fem`` would take; ``jno.rcwa``
reads period, ambients, layers, ε and wavelength out of it. Only the truncation (``orders``, ``grid``) is ours.
"""

import jax

jax.config.update("jax_enable_x64", True)  # modal eigen-decomposition of a high-contrast stack

import jax.numpy as jnp
import numpy as np

import jno

run = jno.setup(__file__)
WL, EPS_RIDGE, DUTY = 1.0, 11.0, 0.5  # wavelength, ridge permittivity (n ≈ 3.3), ridge fraction of the cell
Z0, Z1, PY = 0.4, 0.6, 0.3  # slab z ∈ (0.4, 0.6) in vacuum; y-period sub-wavelength, so a 1-D grating
K0 = 2 * jnp.pi / WL


def grating(period, orders=160, grid=256):
    """Solve one grating; return its efficiencies and the solution."""
    d = jno.shape.box(0, 0, 0, period, PY, 1.0, size=0.25).domain()  # coarse mesh: ε is sampled on the RCWA grid
    x, y, z, _ = d.variable("interior", split=True)
    left, right, front, back, top, bottom = (
        d.variable(s, split=True) for s in ("left", "right", "front", "back", "top", "bottom")
    )
    u = d.unknown()
    v = u.test()
    grad = lambda w: jno.np.jacobian(w, [x, y, z])
    ridge = jno.fn(lambda x, y, z: jnp.where((Z0 < z) & (z < Z1) & (x < DUTY * period), 1.0, 0.0), [x, y, z])
    eps = 1.0 + (EPS_RIDGE - 1.0) * ridge

    rc = jno.rcwa(
        [
            jno.np.inner(grad(u), grad(v)) - K0**2 * eps * u * v,  # ∇u·∇v − k₀²ε u v = 0
            -1j * K0 * u(*top) * v(*top),  # radiation out through the top
            -(1j * K0 * u(*bottom) - 2j * K0) * v(*bottom),  # plane wave in, radiation out at the bottom
            u(*left) - u(*right),  # Floquet periodicity in x
            u(*front) - u(*back),  # and in y
        ],
        orders=orders,
        grid=grid,
    )  # rc.spec holds what was inferred from the list
    sol = rc.solve()

    real = lambda a: float(jnp.real(jnp.asarray(a)))
    return dict(
        T=real(sol.efficiency("T")),
        R=real(sol.efficiency("R")),
        orders={m: real(sol.order(m, 0)) for m in (-2, -1, 0, 1, 2)},
        sol=sol,
    )


propagating = lambda period: [m for m in (-2, -1, 0, 1, 2) if abs(m * WL / period) <= 1.0]  # the grating equation

# --- two regimes: sub-wavelength (Λ < λ) and diffractive (Λ > λ) ---
SUB, DIF = 0.6, 1.5
res = {P: grating(P) for P in (SUB, DIF)}
for P, r in res.items():
    prop, o = propagating(P), r["orders"]
    print(f"Λ = {P}: grating equation allows m ∈ {prop}")
    print(f"  R = {r['R']:.5f}   T = {r['T']:.5f}   R + T = {r['R'] + r['T']:.6f}")
    print("  " + "   ".join(f"T({m:+d}) = {o[m]:.5f}" for m in (-1, 0, 1)))
    assert abs(r["R"] + r["T"] - 1.0) < 1e-6  # lossless: energy is conserved
    assert all(o[m] < 1e-9 for m in o if m not in prop)  # orders the grating equation forbids are dark
    assert abs(o[+1] - o[-1]) < 1e-6  # mirror symmetry at normal incidence (floor ~1e-10, set by the eigensolve)
    assert abs(sum(o[m] for m in prop) - r["T"]) < 1e-6  # the propagating orders carry all of T
assert res[SUB]["orders"][+1] == 0.0  # below the cutoff the ±1 orders are exactly dark
assert res[DIF]["orders"][+1] + res[DIF]["orders"][-1] > 0.8 * res[DIF]["T"]  # above it they take most of T

# --- sweep the period across the Rayleigh anomaly at Λ = λ (Λ = mλ itself is singular: jno.rcwa raises) ---
periods = np.concatenate([np.linspace(0.55, 0.95, 5), np.linspace(1.05, 1.95, 8)])
sweep = [grating(float(P)) for P in periods]
first_on = next(P for P, r in zip(periods, sweep) if r["orders"][+1] > 1e-6)
assert first_on > WL and all(abs(r["R"] + r["T"] - 1.0) < 1e-6 for r in sweep)
print(f"swept {len(periods)} periods; the ±1 orders first carry power at Λ = {first_on:.2f} (cutoff Λ = λ = {WL})")
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/binary_grating_orders.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    dense = np.concatenate([np.linspace(0.55, 0.99, 22), np.linspace(1.01, 1.99, 50)])  # steps around Λ = λ and 2λ
    fine = [grating(float(P)) for P in dense]
    slices = [r["sol"].field(y_frac=0.5, nx=160, density=60.0) for r in fine]  # |E|² on an x-z slice
    np.savez_compressed(
        Path(out) / "binary_grating_orders.npz",
        periods=dense,
        R=[r["R"] for r in fine],
        T0=[r["orders"][0] for r in fine],
        T1=[r["orders"][+1] + r["orders"][-1] for r in fine],
        intensity=np.array([s[0] for s in slices], dtype=np.float32),
        extent_z=np.array([s[1][2:] for s in slices]),
        layer_z=np.array([s[2] for s in slices]),
        slab=np.array([Z0, Z1]),
        duty=DUTY,
    )
