"""Render the rounds 5, 6, and 7 fields as art, same kind as
render_fields_r34.py. Usage: python3 render_fields_r567.py <5|6|7>

Panel 1: Kida-Pelz vorticity magnitude slice (z = pi plane) at peak
enstrophy, evolved with the lab's round 4 real-FFT solver, with
in-plane streamlines overlaid. Panel 2: per-site xy-plaquette values
on one time slice of a thermalized SU(2) lattice, drawn twice as a
woven diamond pattern: once unsmeared, once after 4 APE smearing
steps at alpha 0.5.

Round 5: NS 64^3 nu 0.00025, YM weave beta 2.6.
Round 6: NS 64^3 nu 0.000125, YM weave beta 2.5.
Round 7: NS snapshot comes from the round 7 hunt itself (the full
96^3 Kida-Pelz run captured its peak snapshot); this script only
runs the YM weave at beta 2.6 and assembles the meta.

Everything plotted is computed here from the lab code, except the
round 7 NS snapshot, which was computed by the round 7 hunt run.
Peak time, enstrophy growth, and plaquette means are printed and
written to render_meta_r<N>.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"
ROUND = sys.argv[1]
DT = 0.01
FINAL_TIME = 10.0

CONFIG = {
    "5": {"n": 64, "nu": 0.00025, "beta": 2.6, "rng_seed": 20261121,
          "ns_from_hunt": False},
    "6": {"n": 64, "nu": 0.000125, "beta": 2.5, "rng_seed": 20261121,
          "ns_from_hunt": False},
    "7": {"n": 96, "nu": 0.000125, "beta": 2.6, "rng_seed": 20261122,
          "ns_from_hunt": True},
}
cfg = CONFIG[ROUND]
N = cfg["n"]
NU = cfg["nu"]


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_r%s.npy" % (OUT, ROUND),
            vort_mag[:, :, mid])
    np.save("%s/kida_peak_u_r%s.npy" % (OUT, ROUND), u[:, :, mid])
    np.save("%s/kida_peak_v_r%s.npy" % (OUT, ROUND), 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 R%s META:" % ROUND, json.dumps(meta), flush=True)
    return meta


def plaquette_pair(beta, rng_seed):
    rng = np.random.default_rng(rng_seed)
    lat = Lattice(size=8, beta=beta, 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_r%s.npy" % (OUT, ROUND), plain)
    np.save("%s/ym_plaquette_smeared_r%s.npy" % (OUT, ROUND), smeared)
    meta = {
        "beta": beta, "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 R%s META:" % ROUND, json.dumps(meta), flush=True)
    return meta


if __name__ == "__main__":
    if cfg["ns_from_hunt"]:
        km = json.load(open("%s/ns_meta_r7.json" % OUT))
        for name in ("kida_peak_vortmag_r7.npy", "kida_peak_u_r7.npy",
                     "kida_peak_v_r7.npy"):
            import os
            assert os.path.exists(os.path.join(OUT, name)), \
                "missing hunt snapshot %s" % name
        print("NS round 7 snapshot from the hunt run: peak t = %.1f, "
              "growth %.2f" % (km["peak_time"], km["enstrophy_growth"]),
              flush=True)
    else:
        km = evolve_kida_pelz()
    ym = plaquette_pair(cfg["beta"], cfg["rng_seed"])
    json.dump({"kida_pelz": km, "yang_mills": ym},
              open("%s/render_meta_r%s.json" % (OUT, ROUND), "w"), indent=2)
    print("DONE round %s" % ROUND)
