"""Gaussian-random-field lens planes, their shear, and per-bin galaxy shape catalogs.

Restricted simulation: every plane is an independent Gaussian field with a declared power-law
spectrum on a periodic grid. Shear follows from convergence with the Kaiser-Squires kernel
gamma_hat = exp(2 i phi_ell) kappa_hat (Bartelmann & Schneider 2001, Eq. 3.11 in Fourier form).
Galaxy shapes use the weak-lensing limit e = e_intrinsic + gamma; the reduced-shear correction
(order kappa * gamma) is neglected, as stated in the tutorial.
"""
import numpy as np

ARCMIN = np.pi / (180.0 * 60.0)


def grid_wavevectors(pixels, pixel_arcmin):
    """Angular wavevector components (per radian) on the FFT grid."""
    frequencies = 2.0 * np.pi * np.fft.fftfreq(pixels, d=pixel_arcmin * ARCMIN)
    ell_x, ell_y = np.meshgrid(frequencies, frequencies, indexing="xy")
    return ell_x, ell_y


def plane_power(ell, spectrum):
    """Declared power-law spectrum with a Gaussian high-ell cutoff; zero at ell = 0."""
    power = np.zeros_like(ell)
    positive = ell > 0
    power[positive] = (spectrum["amplitude_at_ell_1000"] * (ell[positive] / 1000.0) ** (-spectrum["slope"])
                       * np.exp(-(ell[positive] / spectrum["ell_cut"]) ** 2))
    return power


def gaussian_plane(rng, pixels, pixel_arcmin, power):
    """Real Gaussian field with <|kappa_hat|^2> = N^2 P / A_pixel (numpy FFT normalisation)."""
    white = rng.standard_normal((pixels, pixels))
    pixel_area = (pixel_arcmin * ARCMIN) ** 2
    return np.fft.ifft2(np.fft.fft2(white) * np.sqrt(power / pixel_area)).real


def shear_from_convergence(convergence, ell_x, ell_y):
    """gamma = gamma1 + i gamma2 from kappa on a periodic grid; the ell = 0 mode is set to zero."""
    ell_squared = ell_x ** 2 + ell_y ** 2
    kernel = np.zeros_like(ell_x, dtype=complex)
    nonzero = ell_squared > 0
    kernel[nonzero] = ((ell_x ** 2 - ell_y ** 2) + 2j * ell_x * ell_y)[nonzero] / ell_squared[nonzero]
    return np.fft.ifft2(kernel * np.fft.fft2(convergence))


def galaxy_catalog(rng, shear, pixel_arcmin, galaxies_per_arcmin2, shape_noise):
    """Uniform galaxy positions; each galaxy samples the shear of the pixel it falls in.

    Returns pixel indices (flattened) and complex observed ellipticities.
    """
    pixels = shear.shape[0]
    side_arcmin = pixels * pixel_arcmin
    count = rng.poisson(galaxies_per_arcmin2 * side_arcmin ** 2)
    column = rng.integers(0, pixels, count)
    row = rng.integers(0, pixels, count)
    flat_index = row * pixels + column
    intrinsic = shape_noise * (rng.standard_normal(count) + 1j * rng.standard_normal(count))
    observed = intrinsic + shear.ravel()[flat_index]
    return flat_index, observed


def simulate_realization(inputs, seed, weights):
    """One realization: plane fields, per-bin convergence and shear, and per-bin catalogs."""
    rng = np.random.default_rng(seed)
    grid = inputs["grid"]
    pixels, pixel_arcmin = grid["pixels_per_side"], grid["pixel_arcmin"]
    ell_x, ell_y = grid_wavevectors(pixels, pixel_arcmin)
    power = plane_power(np.hypot(ell_x, ell_y), inputs["plane_power_spectrum"])
    planes = [plane["convergence_variance_scale"] ** 0.5 * gaussian_plane(rng, pixels, pixel_arcmin, power) for plane in inputs["lens_planes"]]
    bins = []
    for bin_index, source_bin in enumerate(inputs["source_bins"]):
        convergence = sum(weights[bin_index, plane_index] * plane for plane_index, plane in enumerate(planes))
        shear = shear_from_convergence(convergence, ell_x, ell_y)
        flat_index, ellipticity = galaxy_catalog(rng, shear, pixel_arcmin, source_bin["galaxies_per_arcmin2"], inputs["shape_noise_per_component"])
        bins.append({"convergence": convergence, "shear": shear, "pixel_index": flat_index, "ellipticity": ellipticity})
    return {"planes": planes, "bins": bins, "power": power, "ell_x": ell_x, "ell_y": ell_y}
