"""Real-FFT variant of the round 2 pseudo-spectral Navier-Stokes solver.

Same mathematics, same float64 arithmetic, same protocol (2/3
dealiasing, classical RK4, periodic cube [0, 2*pi]^3) as
compute/navier_stokes.py, but the state is carried as real FFTs
(numpy rfftn / irfftn) instead of full complex FFTs. All fields are
real, so each transform moves about half the data and the run costs
about half the CPU. The results are verified against the reference
solver by reproducing the round 4 stability probe (Kida-Pelz, 64^3,
nu = 0.0005, dt = 0.01, final time 1.0) to near machine precision
before any full run uses this solver.

Written for round 4 only. The reference solver is untouched.

No em dashes are used anywhere in this file.
"""

import time

import numpy as np


def build_wavenumbers_rfft(n):
    kx = np.fft.fftfreq(n, d=1.0 / n)
    ky = np.fft.fftfreq(n, d=1.0 / n)
    kz = np.fft.rfftfreq(n, d=1.0 / n)
    kx, ky, kz = np.meshgrid(kx, ky, kz, indexing="ij")
    return kx, ky, kz


def dealias_mask_rfft(kx, ky, kz, n):
    kmax = n // 3
    return (np.abs(kx) <= kmax) & (np.abs(ky) <= kmax) & (kz <= kmax)


def project_divergence_free_rfft(uh, vh, wh, kx, ky, kz, k2):
    k2_safe = np.where(k2 == 0, 1.0, k2)
    div = kx * uh + ky * vh + kz * wh
    factor = div / k2_safe
    factor = np.where(k2 == 0, 0.0, factor)
    return uh - kx * factor, vh - ky * factor, wh - kz * factor


def rhs_rfft(uh, vh, wh, kx, ky, kz, k2, mask, nu, shape):
    u = np.fft.irfftn(uh, s=shape)
    v = np.fft.irfftn(vh, s=shape)
    w = np.fft.irfftn(wh, s=shape)
    dudx = np.fft.irfftn(1j * kx * uh, s=shape)
    dudy = np.fft.irfftn(1j * ky * uh, s=shape)
    dudz = np.fft.irfftn(1j * kz * uh, s=shape)
    dvdx = np.fft.irfftn(1j * kx * vh, s=shape)
    dvdy = np.fft.irfftn(1j * ky * vh, s=shape)
    dvdz = np.fft.irfftn(1j * kz * vh, s=shape)
    dwdx = np.fft.irfftn(1j * kx * wh, s=shape)
    dwdy = np.fft.irfftn(1j * ky * wh, s=shape)
    dwdz = np.fft.irfftn(1j * kz * wh, s=shape)
    nl_u = np.fft.rfftn(u * dudx + v * dudy + w * dudz) * mask
    nl_v = np.fft.rfftn(u * dvdx + v * dvdy + w * dvdz) * mask
    nl_w = np.fft.rfftn(u * dwdx + v * dwdy + w * dwdz) * mask
    du = -nl_u - nu * k2 * uh
    dv = -nl_v - nu * k2 * vh
    dw = -nl_w - nu * k2 * wh
    return project_divergence_free_rfft(du, dv, dw, kx, ky, kz, k2)


def diagnostics_rfft(uh, vh, wh, kx, ky, kz, k2, shape):
    u = np.fft.irfftn(uh, s=shape)
    v = np.fft.irfftn(vh, s=shape)
    w = np.fft.irfftn(wh, s=shape)
    oxh = 1j * (ky * wh - kz * vh)
    oyh = 1j * (kz * uh - kx * wh)
    ozh = 1j * (kx * vh - ky * uh)
    ox = np.fft.irfftn(oxh, s=shape)
    oy = np.fft.irfftn(oyh, s=shape)
    oz = np.fft.irfftn(ozh, s=shape)
    energy = 0.5 * float(np.mean(u**2 + v**2 + w**2))
    enstrophy = 0.5 * float(np.mean(ox**2 + oy**2 + oz**2))
    max_vort = float(np.max(np.sqrt(ox**2 + oy**2 + oz**2)))
    max_vel = float(np.max(np.sqrt(u**2 + v**2 + w**2)))
    return energy, enstrophy, max_vort, max_vel


def run_fields_rfft(u0, v0, w0, n=64, nu=0.0005, dt=0.01, final_time=10.0,
                    record_every=10):
    shape = (n, n, n)
    uh = np.fft.rfftn(u0)
    vh = np.fft.rfftn(v0)
    wh = np.fft.rfftn(w0)
    kx, ky, kz = build_wavenumbers_rfft(n)
    k2 = kx**2 + ky**2 + kz**2
    mask = dealias_mask_rfft(kx, ky, kz, n)
    uh, vh, wh = project_divergence_free_rfft(uh, vh, wh, kx, ky, kz, k2)

    steps = int(round(final_time / dt))
    times = []
    enstrophies = []
    max_vorts = []
    energies = []
    max_vels = []

    def record(t):
        e, ens, mv, mvel = diagnostics_rfft(uh, vh, wh, kx, ky, kz, k2,
                                            shape)
        times.append(t)
        energies.append(e)
        enstrophies.append(ens)
        max_vorts.append(mv)
        max_vels.append(mvel)
        return e, ens, mv, mvel

    t_start = time.time()
    e0, ens0, mv0, mvel0 = record(0.0)
    for step in range(1, steps + 1):
        k1 = rhs_rfft(uh, vh, wh, kx, ky, kz, k2, mask, nu, shape)
        k2s = rhs_rfft(uh + 0.5 * dt * k1[0], vh + 0.5 * dt * k1[1],
                       wh + 0.5 * dt * k1[2], kx, ky, kz, k2, mask, nu,
                       shape)
        k3s = rhs_rfft(uh + 0.5 * dt * k2s[0], vh + 0.5 * dt * k2s[1],
                       wh + 0.5 * dt * k2s[2], kx, ky, kz, k2, mask, nu,
                       shape)
        k4s = rhs_rfft(uh + dt * k3s[0], vh + dt * k3s[1],
                       wh + dt * k3s[2], kx, ky, kz, k2, mask, nu, shape)
        uh = uh + (dt / 6.0) * (k1[0] + 2.0 * k2s[0] + 2.0 * k3s[0] + k4s[0])
        vh = vh + (dt / 6.0) * (k1[1] + 2.0 * k2s[1] + 2.0 * k3s[1] + k4s[1])
        wh = wh + (dt / 6.0) * (k1[2] + 2.0 * k2s[2] + 2.0 * k3s[2] + k4s[2])
        uh, vh, wh = uh * mask, vh * mask, wh * mask
        uh, vh, wh = project_divergence_free_rfft(uh, vh, wh, kx, ky, kz,
                                                  k2)
        if step % record_every == 0 or step == steps:
            record(step * dt)
    runtime = time.time() - t_start

    ens_arr = np.array(enstrophies)
    mv_arr = np.array(max_vorts)
    finite = bool(np.all(np.isfinite(ens_arr)) and np.all(np.isfinite(mv_arr))
                  and np.all(np.isfinite(energies)))
    stayed_smooth = finite
    result = {
        "method": "Pseudo-spectral (real FFT, 2/3 dealiasing) with "
                  "classical 4th-order Runge-Kutta; periodic cube "
                  "[0, 2*pi]^3; enstrophy = 0.5*mean(|omega|^2), "
                  "energy = 0.5*mean(|u|^2)",
        "grid": [n, n, n],
        "viscosity": nu,
        "dt": dt,
        "final_time": final_time,
        "steps": steps,
        "runtime_seconds": round(runtime, 2),
        "enstrophy_initial": float(ens_arr[0]),
        "enstrophy_final": float(ens_arr[-1]),
        "enstrophy_peak": float(np.max(ens_arr)),
        "max_vorticity_initial": float(mv_arr[0]),
        "max_vorticity_final": float(mv_arr[-1]),
        "max_vorticity_peak": float(np.max(mv_arr)),
        "energy_initial": float(energies[0]),
        "energy_final": float(energies[-1]),
        "max_velocity_initial": float(max_vels[0]),
        "max_velocity_final": float(max_vels[-1]),
        "stayed_smooth": stayed_smooth,
        "date": "2026-11-20",
    }
    series = {
        "time": [float(t) for t in times],
        "enstrophy": [float(e) for e in enstrophies],
        "max_vorticity": [float(m) for m in max_vorts],
        "energy": [float(e) for e in energies],
        "max_velocity": [float(m) for m in max_vels],
    }
    return result, series
