"""Render the lab's own fields as art, not illustration.

Panel 1: Kida-Pelz vorticity magnitude slice (z = pi plane) at the moment
of peak enstrophy, evolved with the lab's own pseudo-spectral solver
(navier_stokes.py, 48^3, nu 0.001, 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.py, 8^4, beta 2.3,
400 thermalization sweeps), drawn as a woven diamond pattern.

Everything plotted is computed here from the lab code. Nothing is drawn
from imagination. Peak time, enstrophy growth, and plaquette mean are
printed and also written to render_meta.json.
"""
import json
import sys
import time

import numpy as np

sys.path.insert(0, "/home/hatch/workspace/millennium-lab/compute")
from navier_stokes import (
    build_wavenumbers, dealias_mask, diagnostics, project_divergence_free, rhs,
)
from navier_stokes_hunt import kida_pelz
from wilson_lattice import Lattice, dag

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


def evolve_kida_pelz():
    u0, v0, w0 = kida_pelz(N)
    uh = np.fft.fftn(u0)
    vh = np.fft.fftn(v0)
    wh = np.fft.fftn(w0)
    kx, ky, kz = build_wavenumbers(N)
    k2 = kx**2 + ky**2 + kz**2
    mask = dealias_mask(kx, ky, kz, N)
    uh, vh, wh = project_divergence_free(uh, vh, wh, kx, ky, kz, k2)

    def snapshot():
        u = np.fft.ifftn(uh).real
        v = np.fft.ifftn(vh).real
        w = np.fft.ifftn(wh).real
        oxh = 1j * (ky * wh - kz * vh)
        oyh = 1j * (kz * uh - kx * wh)
        ozh = 1j * (kx * vh - ky * uh)
        ox = np.fft.ifftn(oxh).real
        oy = np.fft.ifftn(oyh).real
        oz = np.fft.ifftn(ozh).real
        return u, v, w, ox, oy, oz

    def enstrophy():
        _e, ens, _mv, _mvel = diagnostics(uh, vh, wh, kx, ky, kz, k2)
        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(uh, vh, wh, kx, ky, kz, k2, mask, NU)
        k2s = rhs(uh + 0.5 * DT * k1[0], vh + 0.5 * DT * k1[1],
                  wh + 0.5 * DT * k1[2], kx, ky, kz, k2, mask, NU)
        k3s = rhs(uh + 0.5 * DT * k2s[0], vh + 0.5 * DT * k2s[1],
                  wh + 0.5 * DT * k2s[2], kx, ky, kz, k2, mask, NU)
        k4s = rhs(uh + DT * k3s[0], vh + DT * k3s[1],
                  wh + DT * k3s[2], kx, ky, kz, k2, mask, NU)
        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(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.npy" % OUT, vort_mag[:, :, mid])
    np.save("%s/kida_peak_u.npy" % OUT, u[:, :, mid])
    np.save("%s/kida_peak_v.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-PEELZ META:", json.dumps(meta), flush=True)
    return meta


def plaquette_slice():
    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
    # Per-site xy plaquette at z=0, t=0: U_x U_y(x+x) U_x^dag(x+y) U_y^dag.
    # U[mu] axes are (x, y, z, t, 2, 2); slice [:, :, 0, 0] keeps (x, y).
    ux = U[0][:, :, 0, 0]
    uy = 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_slice.npy" % OUT, vals)
    meta = {
        "beta": 2.3, "lattice": "8^4", "thermalization_sweeps": 400,
        "slice": "xy plane at z=0, t=0",
        "plaquette_mean_slice": float(vals.mean()),
        "plaquette_min": float(vals.min()),
        "plaquette_max": float(vals.max()),
        "runtime_seconds": round(time.time() - t0, 1),
    }
    print("YM META:", json.dumps(meta), flush=True)
    return meta


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