"""Independent optical reference equations and exact rectangular partitions.

No LESS imports. Directions use east/south/up coordinates, with azimuth measured
clockwise from north. RPV follows the RAMI definition; Cox-Munk uses the published
Gaussian slope variances and the Beckmann Smith rational approximation.
"""
import math
import numpy as np


def direction(zenith, azimuth):
    z, a = np.deg2rad([zenith, azimuth])
    return np.array([np.sin(z)*np.sin(a), -np.sin(z)*np.cos(a), np.cos(z)])


def rpv(wi, wo, rho0, k, theta, rhoc):
    cosine = float(np.clip(wi@wo, -1, 1))
    tangent_i, tangent_o = wi[:2]/wi[2], wo[:2]/wo[2]
    distance = np.linalg.norm(tangent_i-tangent_o)
    minnaert = (wi[2]*wo[2]*(wi[2]+wo[2]))**(k-1)
    phase = (1-theta*theta)/(1+theta*theta+2*theta*cosine)**1.5
    return rho0*minnaert*phase*(1+(1-rhoc)/(1+distance))


def fresnel(cosine, index):
    transmitted = math.sqrt(1-(1-cosine*cosine)/index**2)
    perpendicular = ((cosine-index*transmitted)/(cosine+index*transmitted))**2
    parallel = ((index*cosine-transmitted)/(index*cosine+transmitted))**2
    return (perpendicular+parallel)/2


def water(wi, wo, wind_speed, wind_azimuth, index=1.34, rrs=0.):
    half = wi+wo
    half /= np.linalg.norm(half)
    wind = direction(90., wind_azimuth)[:2]
    cross = np.array([-wind[1], wind[0]])
    variance = np.array([.00316*wind_speed, .003+.00192*wind_speed])
    slope = np.array([half[:2]@wind, half[:2]@cross])/half[2]
    density = math.exp(-.5*np.sum(slope*slope/variance))/(2*np.pi*np.sqrt(np.prod(variance)))
    def smith(d):
        tangent = math.sqrt(max(0., 1-d[2]**2))/d[2]
        if tangent < 1e-12:
            return 1.
        azimuth = d[:2]/np.linalg.norm(d[:2])
        alpha = math.sqrt(2*(variance[0]*(azimuth@wind)**2+variance[1]*(azimuth@cross)**2))
        a = 1/(alpha*tangent)
        return 1. if a >= 1.6 else (3.535*a+2.181*a*a)/(1+2.276*a+2.577*a*a)
    return rrs+fresnel(float(wi@half), index)*density/half[2]**4*smith(wi)*smith(wo)/(4*wi[2]*wo[2])


def rectangle_view_factor(a, b, height):
    x, y = math.sqrt(a*a+height*height), math.sqrt(b*b+height*height)
    return 2/math.pi*(a/x*math.atan(b/x)+b/y*math.atan(a/y))


def component_image(config, case):
    """Exact piecewise-constant class areas, by partitioning rectangle edges."""
    size, pixels = config["size_m"], config["image_size"]
    view = math.tan(math.radians(case["view_zenith"]))*case.get("view_sign", 1)
    sun = math.tan(math.radians(case["sun_zenith"]))*case.get("sun_sign", 1)
    copies = (-size, 0., size) if case.get("periodic", False) else (0.,)
    leaves = config["leaves"]
    boundaries_x, boundaries_y = [0., size], [0., size]
    for leaf in leaves:
        for shift in copies:
            boundaries_x += [x-leaf["height_m"]*view+shift for x in leaf["x_m"]]
            boundaries_y += leaf["y_m"]
            for target in [0.]+[p["height_m"] for p in leaves if p["height_m"] < leaf["height_m"]]:
                boundaries_x += [x-(leaf["height_m"]-target)*sun-target*view+shift
                                 for x in leaf["x_m"]]
    grid = np.linspace(0, size, pixels+1)
    xs = np.unique(np.clip(np.r_[boundaries_x, grid], 0, size))
    ys = np.unique(np.clip(np.r_[boundaries_y, grid], 0, size))
    result = np.zeros((pixels, pixels, 4))
    ordered = sorted(leaves, key=lambda p: -p["height_m"])
    def contains(leaf, x, y):
        return any(leaf["x_m"][0]+shift < x < leaf["x_m"][1]+shift
                   for shift in copies) and leaf["y_m"][0] < y < leaf["y_m"][1]
    for left, right in zip(xs[:-1], xs[1:]):
        for bottom, top in zip(ys[:-1], ys[1:]):
            if right == left or top == bottom:
                continue
            x, y = (left+right)/2, (bottom+top)/2
            hit = next((p for p in ordered if contains(p, x+p["height_m"]*view, y)), None)
            z = 0. if hit is None else hit["height_m"]
            world_x = x+z*view
            shaded = any(p["height_m"] > z and
                contains(p, world_x+(p["height_m"]-z)*sun, y) for p in leaves)
            category = (0 if hit is None else 1)+(2 if shaded else 0)
            column = min(pixels-1, int(x/size*pixels))
            row = min(pixels-1, int(y/size*pixels))
            result[row, column, category] += (right-left)*(top-bottom)/(size/pixels)**2
    return result


def clip_polygon(polygon, left, right, bottom, top):
    polygon = list(map(np.asarray, polygon))
    for axis, edge, sign in ((0, left, 1), (0, right, -1), (1, bottom, 1), (1, top, -1)):
        output = []
        for a, b in zip(polygon, polygon[1:]+polygon[:1]):
            ia, ib = sign*(a[axis]-edge)>=0, sign*(b[axis]-edge)>=0
            if ia:
                output.append(a)
            if ia != ib:
                output.append(a+(b-a)*(edge-a[axis])/(b[axis]-a[axis]))
        polygon = output
        if not polygon:
            return 0.
    values = np.asarray(polygon)
    return float(abs(np.sum(values[:, 0]*np.roll(values[:, 1], -1)
                            -values[:, 1]*np.roll(values[:, 0], -1)))/2)


def calibration_image(c, name, tolerance=2e-11):
    from scipy.integrate import quad
    from scipy.optimize import brentq
    n, height = c["image_size"], c["altitude_m"]
    center = np.asarray(c["center_m"])
    output = np.zeros((n, n))
    if name.startswith("fisheye_"):
        model = name.removeprefix("fisheye_")
        half = math.radians(c["fisheye_fov"])/2
        def zenith(radius):
            if model == "equisolid":
                return 2*math.asin(radius*math.sin(half/2))
            if model == "equidistant":
                return radius*half
            if model == "orthographic":
                return math.asin(radius*math.sin(half))
            return 2*math.atan(radius*math.tan(half/2))
        def area(i, j, lo=None, hi=None):
            u0, u1, v0, v1 = i*2/n-1, (i+1)*2/n-1, j*2/n-1, (j+1)*2/n-1
            def width(v):
                maximum = math.sqrt(max(0., 1-v*v))
                if maximum == 0:
                    return 0.
                def boundary(x):
                    outer = height*math.tan(half)*maximum
                    if x <= -outer:
                        return -maximum
                    if x >= outer:
                        return maximum
                    def f(u):
                        radius = math.hypot(u, v)
                        return height*math.tan(zenith(radius))*u/radius-x if radius else -x
                    return brentq(f, -maximum, maximum, xtol=1e-13)
                left, right = (-maximum, maximum) if lo is None else (boundary(lo), boundary(hi))
                return max(0., min(u1, right)-max(u0, left))
            return quad(width, v0, v1, epsabs=tolerance, epsrel=1e-10, limit=150)[0]*n*n/4
        for j in range(n):
            for i in range(n):
                value = (c["x_reflectance"][0]+c["y_reflectance"][0])*area(i, j)
                for axis, ii, jj in (("x", i, j), ("y", j, i)):
                    edges, rho = c[axis+"_edges_m"], c[axis+"_reflectance"]
                    offset = center[0 if axis=="x" else 1]
                    for lo, hi, r in zip(edges[:-1], edges[1:], rho):
                        if r != rho[0]:
                            value += (r-rho[0])*area(ii, jj, lo-offset, hi-offset)
                output[j, i] = value
        return output
    if name.startswith("perspective"):
        position = np.array([10., 10., height]) if name == "perspective" else np.array([9., 10., 6.])
        target = np.array([10., 10., 0.])
        forward = target-position
        forward /= np.linalg.norm(forward)
        right = np.cross([0., -1., 0.], forward)
        right /= np.linalg.norm(right)
        down = np.cross(right, forward)
        tangent = c["extent_m"]/(2*height) if name == "perspective" else math.tan(math.radians(60)/2)
        def project(x, y):
            relative = np.array([x, y, 0.])-position
            denominator = 2*tangent*(relative@forward)
            return [.5+(relative@right)/denominator, .5+(relative@down)/denominator]
    for yi, (b, t) in enumerate(zip(c["y_edges_m"][:-1], c["y_edges_m"][1:])):
        for xi, (l, r) in enumerate(zip(c["x_edges_m"][:-1], c["x_edges_m"][1:])):
            reflectance = c["x_reflectance"][xi]+c["y_reflectance"][yi]
            if name.startswith("perspective"):
                polygon = [project(x, y) for x, y in ((l, b), (r, b), (r, t), (l, t))]
                for j in range(n):
                    for i in range(n):
                        output[j, i] += reflectance*clip_polygon(polygon, i/n, (i+1)/n,
                                                                 j/n, (j+1)/n)*n*n
            else:
                if name == "orthographic":
                    u = [(l-center[0])/c["extent_m"]+.5, (r-center[0])/c["extent_m"]+.5]
                    v = [(b-center[1])/c["extent_m"]+.5, (t-center[1])/c["extent_m"]+.5]
                elif name == "pushbroom_0":
                    fov = 2*math.atan(c["extent_m"]/(2*height))
                    u = [math.atan((x-center[0])/height)/fov+.5 for x in (l, r)]
                    v = [.5-(y-center[1])/c["extent_m"] for y in (b, t)]
                else:
                    fov = 2*math.atan(c["extent_m"]/(2*height))
                    u = [math.atan((y-center[1])/height)/fov+.5 for y in (b, t)]
                    v = [(x-center[0])/c["extent_m"]+.5 for x in (l, r)]
                left, right = sorted(u)
                bottom, top = sorted(v)
                x_overlap = np.maximum(0., np.minimum((np.arange(n)+1)/n, right)
                                       -np.maximum(np.arange(n)/n, left))
                y_overlap = np.maximum(0., np.minimum((np.arange(n)+1)/n, top)
                                       -np.maximum(np.arange(n)/n, bottom))
                output += reflectance*y_overlap[:, None]*x_overlap[None, :]*n*n
    return output
