"""Render the rounds 3/4 fields as art, same kind as render_fields.py.

Panel 1: Kida-Pelz vorticity magnitude slice (z = pi plane) at peak
enstrophy, evolved with the lab's round 4 real-FFT solver
(navier_stokes_r4.py, 64^3, nu 0.0005, dt 0.01, t to 10), with in-plane
streamlines overlaid. Panel 2: per-site xy-plaquette values on one time
slice of a thermalized SU(2) lattice (wilson_lattice_r4.py, 8^4, beta 2.3,
400 sweeps), drawn twice as a woven diamond pattern: once unsmeared, once
after 4 APE smearing steps at alpha 0.5, the operator improvement that
cleaned up the 0++ gap in round 4.

Everything plotted is computed here from the lab code. Peak time,
enstrophy growth, and plaquette means are printed and written to
render_meta_r34.json.
"""
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, ape_step, dag, APE_ALPHA

OUT = "/home/hatch/workspace/millennium-lab/poster"
N = 64
NU = 0.0005
DT = 0.01
FINAL_TIME = 10.0


def evolve_kida_pelz():
    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)
        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)
        return u, v, w, 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 % 200 == 0:
            print("step %d t=%.2f ens=%.3f elapsed=%.0fs"
                  % (step, step * DT, ens, time.time() - t0), flush=True)
    u, v, w, ox, oy, oz = best
    mid = N // 2
    vort_mag = np.sqrt(ox**2 + oy**2 + oz**2)
    np.save("%s/kida_peak_vortmag_r34.npy" % OUT, vort_mag[:, :, mid])
    np.save("%s/kida_peak_u_r34.npy" % OUT, u[:, :, mid])
    np.save("%s/kida_peak_v_r34.npy" % OUT, 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("KIDA-PELZ R34 META:", json.dumps(meta), flush=True)
    return meta


def plaquette_pair():
    rng = np.random.default_rng(20261120)
    lat = Lattice(size=8, beta=2.3, rng=rng)
    t0 = time.time()
    for s in range(400):
        lat.sweep()
    U = lat.U

    def xy_slice(U3):
        ux = U3[0][:, :, 0, 0]
        uy = U3[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)),
        )
        return 0.5 * np.real(np.trace(p, axis1=-2, axis2=-1))

    plain = xy_slice(U[0:3])
    U3 = np.array(U[0:3])
    for _ in range(4):
        U3 = ape_step(U3, APE_ALPHA)
    smeared = xy_slice(U3)
    np.save("%s/ym_plaquette_plain_r34.npy" % OUT, plain)
    np.save("%s/ym_plaquette_smeared_r34.npy" % OUT, smeared)
    meta = {
        "beta": 2.3, "lattice": "8^4", "thermalization_sweeps": 400,
        "smearing": "APE alpha 0.5, 4 steps, spatial links only",
        "slice": "xy plane at z=0, t=0",
        "plain_mean": float(plain.mean()),
        "plain_min": float(plain.min()),
        "plain_max": float(plain.max()),
        "smeared_mean": float(smeared.mean()),
        "smeared_min": float(smeared.min()),
        "smeared_max": float(smeared.max()),
        "runtime_seconds": round(time.time() - t0, 1),
    }
    print("YM R34 META:", json.dumps(meta), flush=True)
    return meta


if __name__ == "__main__":
    km = evolve_kida_pelz()
    ym = plaquette_pair()
    json.dump({"kida_pelz": km, "yang_mills": ym},
              open("%s/render_meta_r34.json" % OUT, "w"), indent=2)
    print("DONE")
