"""Evolve the fields still missing for the per-round renders.

- R2 NS: Kida-Pelz 64^3, nu 0.001, dt 0.01, T 10 (round 2's 64^3 run,
  growth 18.86 in the lab data).
- R3 NS: Kida-Pelz 64^3, nu 0.001, dt 0.01, T 20 (round 3's long run,
  peak enstrophy 21.2164 in the lab data).
- R1 YM: SU(2) 8^4, beta 2.2, 400 sweeps, per-site xy plaquette slice.
- R3 YM: SU(2) 8^4, beta 2.5, 400 sweeps, per-site xy plaquette slice.

Uses the lab's round 4 real-FFT solver and the round 4 lattice code.
Slices and render_meta_r2r3.json are written to the poster directory.
"""
import json
import sys
import time

import numpy as np

sys.path.insert(0, "/home/hatch/workspace/millennium-lab/compute")
from navier_stokes_r4 import (
    build_wavenumbers_rfft, dealias_mask_rfft, diagnostics_rfft,
    project_divergence_free_rfft, rhs_rfft,
)
from navier_stokes_hunt import kida_pelz
from wilson_lattice_r4 import Lattice, dag

OUT = "/home/hatch/workspace/millennium-lab/poster"
N = 64
DT = 0.01


def evolve(tag, nu, final_time):
    u0, v0, w0 = kida_pelz(N)
    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)

    def snapshot():
        u = np.fft.irfftn(uh, s=shape)
        v = np.fft.irfftn(vh, 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)
        return u, v, ox, oy, oz

    def enstrophy():
        _e, ens, _mv, _mvel = diagnostics_rfft(uh, vh, wh, kx, ky, kz, k2,
                                               shape)
        return ens

    steps = int(round(final_time / DT))
    ens0 = enstrophy()
    best_ens = ens0
    best_t = 0.0
    best = snapshot()
    t0 = time.time()
    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 % 10 == 0 or step == steps:
            ens = enstrophy()
            if ens > best_ens:
                best_ens = ens
                best_t = step * DT
                best = snapshot()
        if step % 400 == 0:
            print("%s step %d t=%.2f ens=%.3f elapsed=%.0fs"
                  % (tag, step, step * DT, ens, time.time() - t0),
                  flush=True)
    u, v, ox, oy, oz = best
    mid = N // 2
    vort_mag = np.sqrt(ox**2 + oy**2 + oz**2)
    np.save("%s/kida_peak_vortmag_%s.npy" % (OUT, tag), vort_mag[:, :, mid])
    np.save("%s/kida_peak_u_%s.npy" % (OUT, tag), u[:, :, mid])
    np.save("%s/kida_peak_v_%s.npy" % (OUT, tag), v[:, :, mid])
    meta = {
        "grid": N, "nu": nu, "dt": DT, "final_time": final_time,
        "enstrophy_initial": float(ens0),
        "enstrophy_peak": float(best_ens),
        "enstrophy_growth": float(best_ens / ens0),
        "peak_time": float(best_t),
        "slice": "z = pi plane, index %d" % mid,
        "max_vorticity_peak_slice": float(vort_mag[:, :, mid].max()),
        "runtime_seconds": round(time.time() - t0, 1),
    }
    print("%s META: %s" % (tag, json.dumps(meta)), flush=True)
    return meta


def plaquette(tag, beta):
    rng = np.random.default_rng(20261120)
    lat = Lattice(size=8, beta=beta, rng=rng)
    t0 = time.time()
    for _ in range(400):
        lat.sweep()
    ux = lat.U[0][:, :, 0, 0]
    uy = lat.U[1][:, :, 0, 0]
    p = np.matmul(
        np.matmul(ux, np.roll(uy, -1, axis=0)),
        np.matmul(dag(np.roll(ux, -1, axis=1)), dag(uy)),
    )
    vals = 0.5 * np.real(np.trace(p, axis1=-2, axis2=-1))
    np.save("%s/ym_plaquette_%s.npy" % (OUT, tag), vals)
    meta = {
        "beta": beta, "lattice": "8^4", "thermalization_sweeps": 400,
        "slice": "xy plane at z=0, t=0",
        "mean": float(vals.mean()), "min": float(vals.min()),
        "max": float(vals.max()),
        "runtime_seconds": round(time.time() - t0, 1),
    }
    print("%s META: %s" % (tag, json.dumps(meta)), flush=True)
    return meta


if __name__ == "__main__":
    out = {}
    out["r2_ns"] = evolve("r2", 0.001, 10.0)
    out["r3_ns"] = evolve("r3", 0.001, 20.0)
    out["r1_ym"] = plaquette("r1", 2.2)
    out["r3_ym"] = plaquette("r3", 2.5)
    json.dump(out, open("%s/render_meta_r2r3.json" % OUT, "w"), indent=2)
    print("DONE")
