"""A14: calibration-target projections, spectral interpolation and band response."""
import json
import math
import numpy as np
import less
import validation_support as support

NAME = "sensor-response"
REF = support.reference("optical_validation")
CASES = ("orthographic", "perspective", "perspective_tilted", "pushbroom_0", "pushbroom_90",
         "fisheye_equisolid", "fisheye_equidistant", "fisheye_orthographic", "fisheye_stereographic")


def geometry(c, name):
    n, height = c["image_size"], c["altitude_m"]
    if name == "orthographic":
        return less.Orthographic(image_size=n, extent=c["extent_m"], altitude=height,
                                 center=tuple(c["center_m"]))
    if name.startswith("perspective"):
        tilted = name.endswith("tilted")
        return less.Perspective(resolution=n, position=(9, 10, 6) if tilted else (10, 10, height),
            target=(10, 10, 0), up=(0, -1, 0),
            fov=60 if tilted else math.degrees(2*math.atan(c["extent_m"]/(2*height))))
    if name.startswith("pushbroom"):
        return less.Pushbroom(resolution=n, num_lines=n, altitude=height,
            swath_width=c["extent_m"], ground_track_length=c["extent_m"],
            heading=float(name.split("_")[1]), center=tuple(c["center_m"]),
            line_rate=2, start_time=10)
    return less.Fisheye(resolution=n, position=(*c["center_m"], height), orientation="down",
        up=(0, -1, 0), fov=c["fisheye_fov"], projection=name.removeprefix("fisheye_"))


def scene_for(c, backend):
    scene = less.Scene(backend=backend)
    scene.size, scene.repetitive, scene.measurement_plane = c["size_m"], False, 0
    scene.terrain = None
    target = less.Object("target")
    for j, y in enumerate(c["y_reflectance"]):
        for i, x in enumerate(c["x_reflectance"]):
            name = f"tile_{j}_{i}"
            target.add_component(name, less.Mesh(str(support.DATA/NAME/"target.obj"), group=name))
            target.set_property(name, less.Lambertian(reflectance=x+y))
    scene.add(target, positions=[(0, 0, 0)])
    scene.illumination = less.Illumination(source=less.Sun(zenith=0, irradiance=1),
                                         atmosphere=less.NoAtmosphere())
    return scene


def geolocation_error(product, c, name):
    n, h = c["image_size"], c["altitude_m"]
    u = (np.arange(n)+.5)/n-.5
    scan = h*np.tan(u*2*math.atan(c["extent_m"]/(2*h)))
    along = u*c["extent_m"]
    if name == "pushbroom_0":
        x, y = np.broadcast_arrays(c["center_m"][0]+scan[None, :],
                                    c["center_m"][1]-along[:, None])
    else:
        x, y = np.broadcast_arrays(c["center_m"][0]+along[:, None],
                                    c["center_m"][1]+scan[None, :])
    geo = product.geolocation
    error = max(float(np.max(abs(np.asarray(geo[k])-v))) for k, v in (("x", x), ("y", y)))
    time_error = float(np.max(abs(np.asarray(geo["time"])-(10+np.arange(n)/2)[:, None])))
    return error, time_error


def spectral(c, backend):
    s = c["spectral"]
    scene = less.Scene(backend=backend)
    scene.size, scene.repetitive = 20, True
    scene.terrain = less.Terrain(property=less.Lambertian(wavelengths=s["wavelengths"],
                                                         reflectance=s["reflectance"]))
    scene.illumination = less.Illumination(source=less.Sun(zenith=0,
        wavelengths=s["wavelengths"], irradiance=s["irradiance"]), atmosphere=less.NoAtmosphere())
    wave = np.array(s["requested"])
    expected = (.001*wave-.3)*(.002*wave+.2)/np.pi
    p = scene.simulate(less.OpticalImager(less.Orthographic(image_size=2), bands=list(wave), quality=1))
    identity = support.execution(p, backend, "optical_backward", "optical_backward")
    discrete = np.asarray(p.data, float).mean(axis=(0, 1))
    triangles = np.array(s["srf_wavelengths"], float)
    a, b, d = triangles.T
    mean = (a+b+d)/3
    moment2 = (a*a+b*b+d*d+a*b+a*d+b*d)/6
    reference = (2e-6*moment2-.0004*mean-.06)/np.pi
    bands = less.SRFBands(band_names=["green", "red"], band_centers=mean,
        band_srf_wavelengths=[np.array(v) for v in s["srf_wavelengths"]],
        band_srf_responses=[np.array(v) for v in s["srf_responses"]])
    levels = []
    for step in s["resolutions_nm"]:
        p = scene.simulate(less.OpticalImager(less.Orthographic(image_size=2), bands=bands,
                                            spectral_resolution=step, quality=1))
        support.execution(p, backend, "optical_backward", "optical_backward")
        values = np.asarray(p.data, float).mean(axis=(0, 1))
        levels.append(dict(step_nm=step, radiance=values.tolist(),
                           maximum_error=float(np.max(abs(values-reference)))))
    del scene
    maximum = max(float(np.max(abs(discrete-expected))), levels[-1]["maximum_error"])
    return dict(backend=backend, discrete_reference=expected.tolist(), discrete=discrete.tolist(),
        srf_reference=reference.tolist(), integration=levels, execution=identity,
        maximum_error=maximum, passed=maximum <= c["thresholds"]["spectral_radiance"])


def run(c, backends=support.BACKENDS):
    references = {name: REF.calibration_image(c, name) for name in CASES}
    integration_check = max(float(np.max(abs(references[name]-REF.calibration_image(c, name, 2e-13))))
        for name in CASES if name.startswith("fisheye"))
    assert integration_check <= c["thresholds"]["reference_integral"], integration_check
    records, sampling, spectra = [], [], []
    for backend in backends:
        scene = scene_for(c, backend)
        for name in CASES:
            levels = []
            for quality in c["quality_levels"]:
                replicas, images = [], []
                for seed in c["seeds"]:
                    scene.sampler = less.Sampler("sobol", seed=seed)
                    p = scene.simulate(less.OpticalImager(geometry(c, name), bands=[550], quality=quality))
                    identity = support.execution(p, backend, "optical_backward", "optical_backward")
                    image = np.asarray(p.to_brf().data[..., 0], float)
                    images.append(image)
                    replicas.append(dict(seed=seed, rmse=float(np.sqrt(np.mean((image-references[name])**2))),
                                         execution=identity))
                mean = np.mean(images, axis=0)
                error = mean-references[name]
                levels.append(dict(samples=quality, rmse=float(np.sqrt(np.mean(error**2))),
                                   maximum_error=float(np.max(abs(error)))))
                if len(levels) == len(c["quality_levels"])-1:
                    previous = mean
            delta = float(np.sqrt(np.mean((mean-previous)**2)))
            geo, timing = geolocation_error(p, c, name) if name.startswith("pushbroom") else (0., 0.)
            row = dict(backend=backend, case=name, image=mean.tolist(), repeats=replicas,
                rmse=levels[-1]["rmse"], maximum_error=levels[-1]["maximum_error"],
                sampling_change=delta, geolocation_error_m=geo, time_error_s=timing,
                passed=bool(levels[-1]["rmse"] <= c["thresholds"]["image_rmse"] and
                    levels[-1]["maximum_error"] <= c["thresholds"]["image_max"] and
                    delta <= c["thresholds"]["last_change"] and
                    geo <= c["thresholds"]["geolocation_m"] and timing <= 1e-6))
            records.append(row)
            sampling.append(dict(backend=backend, case=name, levels=levels))
            print(backend, name, row["passed"], row["rmse"], row["maximum_error"], flush=True)
        del scene
        spectra.append(spectral(c, backend))
    return dict(input=c, references={k:v.tolist() for k,v in references.items()},
        reference_integration_change=integration_check, records=records, sampling=sampling,
        spectral=spectra, passed=all(r["passed"] for r in records+spectra))


def figures(result, output):
    plt = support.plot_settings()
    fig, axes = plt.subplots(2, 3, figsize=(12, 7), layout="constrained")
    for row, (name, label) in enumerate((("perspective_tilted", "Tilted perspective"),
                                       ("fisheye_equisolid", "Equisolid fisheye"))):
        reference = np.array(result["references"][name])
        actual = np.array(next(r["image"] for r in result["records"] if r["case"]==name))
        for ax, image, title in zip(axes[row], (reference, actual, actual-reference),
                (label+" reference", "LESS (OptiX)", "BRF error")):
            im = ax.imshow(image, cmap="coolwarm" if title=="BRF error" else "viridis",
                vmin=-.002 if title=="BRF error" else 0, vmax=.002 if title=="BRF error" else .8)
            ax.set(title=title, xlabel="Column", ylabel="Row")
            fig.colorbar(im, ax=ax, shrink=.8)
    fig.savefig(output/"images.svg")
    plt.close(fig)
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.8), layout="constrained")
    support.convergence(axes[0], result["sampling"], ylabel="Image BRF RMSE")
    for row, color, marker in zip(result["spectral"], support.COLORS, support.MARKERS):
        axes[1].loglog([v["step_nm"] for v in row["integration"]],
            [v["maximum_error"] for v in row["integration"]], marker=marker, color=color,
            markerfacecolor="none", label=row["backend"])
    axes[1].set(xlabel="Spectral integration step / nm", ylabel="Band radiance error")
    axes[1].legend(frameon=False)
    fig.savefig(output/"convergence.svg")
    plt.close(fig)


if __name__ == "__main__":
    args = support.arguments(NAME)
    result = (json.loads((args.output/"results.json").read_text()) if args.figures_only else
        run(support.inputs(NAME), [args.backend] if args.backend else support.BACKENDS))
    support.write_result(args.output, result)
    if args.backend is None:
        figures(result, args.output)
    raise SystemExit(0 if result["passed"] else 1)
