"""Navier-Stokes round 7: full 96^3 at nu = 0.000125, plus longer-time
Taylor-Green at 64^3.

Move 1: full 96^3 runs, Kida-Pelz and Taylor-Green, nu 0.000125,
dt 0.01, T = 10 (1000 steps). A short cost probe (10 steps of
Kida-Pelz at 96^3) runs first to confirm the Round 6 probe
(1.716 s/step, full run about 0.48 h). The Kida-Pelz 96^3 run
captures the peak-enstrophy field snapshot for the round 7 poster
render, using a snapshot loop verified bit-identical to the Round 4
solver at 32^3 before the production run. If the validation fails,
the Kida-Pelz 96^3 case runs on the plain Round 4 solver and the
render gets its own evolution pass.

Move 2: Taylor-Green at 64^3, nu 0.000125, to T = 20 (2000 steps).
Round 6 left it still rising at T = 10; this tests whether it peaks
and decays like Kida-Pelz or keeps rising.

Dual run: the strongest case (by max vorticity growth) is rerun once
and the case dicts are hashed (excluding wall-clock fields) to check
determinism.

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

import hashlib
import json
import os
import resource
import sys
import time

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from navier_stokes import taylor_green  # noqa: E402
from navier_stokes_r4 import (  # noqa: E402
    build_wavenumbers_rfft,
    dealias_mask_rfft,
    diagnostics_rfft,
    project_divergence_free_rfft,
    rhs_rfft,
    run_fields_rfft,
)
from navier_stokes_hunt import (  # noqa: E402
    kida_pelz,
    perturbed_taylor_green,
    summarise,
)

POSTER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
                      "poster")


def run_fields_rfft_snapshot(u0, v0, w0, n=96, nu=0.000125, dt=0.01,
                             final_time=10.0, record_every=10):
    """Mirror of run_fields_rfft that also captures the peak-enstrophy
    field snapshot (u, v, w, vorticity) at record steps.

    The stepping loop is copied verbatim from navier_stokes_r4.py so
    the result dict matches run_fields_rfft bit for bit; the only
    additions are the snapshot bookkeeping. Validated against
    run_fields_rfft at 32^3 before any production use.
    """
    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 fields():
        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 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

    best_ens = -1.0
    best_t = 0.0
    best = None

    def record_with_snapshot(t):
        nonlocal best_ens, best_t, best
        _e, ens, _mv, _mvel = record(t)
        if ens > best_ens:
            best_ens = ens
            best_t = t
            best = fields()
        return ens

    t_start = time.time()
    record_with_snapshot(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_with_snapshot(step * dt)
        if step % 200 == 0:
            print("  snapshot-loop step %d t=%.2f elapsed=%.0fs"
                  % (step, step * dt, time.time() - t_start), flush=True)
    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],
    }
    snapshot = {
        "u": best[0], "v": best[1], "w": best[2],
        "ox": best[3], "oy": best[4], "oz": best[5],
        "peak_time": float(best_t),
        "peak_enstrophy": float(best_ens),
    }
    return result, series, snapshot


def validate_snapshot_loop():
    """Compare the snapshot loop against run_fields_rfft at 32^3.

    Every result field except runtime_seconds must match exactly.
    Returns True when identical.
    """
    print("validating snapshot loop at 32^3, Kida-Pelz, nu 0.000125, "
          "T = 1.0", flush=True)
    u0, v0, w0 = kida_pelz(32)
    r1, _s1 = run_fields_rfft(u0, v0, w0, n=32, nu=0.000125, dt=0.01,
                              final_time=1.0)
    u0, v0, w0 = kida_pelz(32)
    r2, _s2, _snap = run_fields_rfft_snapshot(
        u0, v0, w0, n=32, nu=0.000125, dt=0.01, final_time=1.0)
    mismatches = []
    for key in r1:
        if key == "runtime_seconds":
            continue
        if r1[key] != r2[key]:
            mismatches.append((key, r1[key], r2[key]))
    if mismatches:
        print("snapshot loop validation FAILED: %s" % mismatches, flush=True)
        return False
    print("snapshot loop validation PASSED: all result fields identical",
          flush=True)
    return True


def cost_probe_96(nu, dt, steps=10):
    """10 steps of Kida-Pelz at 96^3, confirming the Round 6 probe."""
    print("96^3 cost probe: kida-pelz, %d steps, nu = %.6f" % (steps, nu),
          flush=True)
    rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    t0 = time.time()
    u0, v0, w0 = kida_pelz(96)
    result, _series = run_fields_rfft(u0, v0, w0, n=96, nu=nu, dt=dt,
                                      final_time=steps * dt)
    wall = time.time() - t0
    rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    per_step = wall / steps
    probe = {
        "grid": [96, 96, 96],
        "solver": "Round 4 real-FFT solver (compute/navier_stokes_r4.py)",
        "steps": steps,
        "nu": nu,
        "dt": dt,
        "wall_seconds": round(wall, 2),
        "per_step_seconds": round(per_step, 3),
        "peak_rss_mb_before": round(rss_before / 1024.0, 1),
        "peak_rss_mb_after": round(rss_after / 1024.0, 1),
        "extrapolated_1000_steps_seconds": round(per_step * 1000, 1),
        "extrapolated_1000_steps_hours": round(per_step * 1000 / 3600, 2),
        "stayed_smooth": result["stayed_smooth"],
        "round6_probe_per_step_seconds": 1.716,
        "note": "Confirmation of the Round 6 probe (1.716 s/step, full "
                "run about 0.48 h, peak RSS 379.4 MB) before the full "
                "96^3 runs.",
    }
    print(json.dumps(probe, indent=2), flush=True)
    return probe


def run_case(name, description, field_fn, nu, dt, final_time, n=64,
             snapshot=False):
    print("round 7 case: %s at %d^3, nu = %.6f, T = %.1f"
          % (name, n, nu, final_time), flush=True)
    t0 = time.time()
    u0, v0, w0 = field_fn(n)
    snap = None
    if snapshot:
        result, series, snap = run_fields_rfft_snapshot(
            u0, v0, w0, n=n, nu=nu, dt=dt, final_time=final_time)
    else:
        result, series = run_fields_rfft(u0, v0, w0, n=n, nu=nu, dt=dt,
                                         final_time=final_time)
    wall = time.time() - t0
    case = summarise(name, description, result)
    ens = series["enstrophy"]
    times = series["time"]
    peak_idx = int(max(range(len(ens)), key=lambda i: ens[i]))
    case["enstrophy_peak_time"] = float(times[peak_idx])
    mv = series["max_vorticity"]
    mv_peak_idx = int(max(range(len(mv)), key=lambda i: mv[i]))
    case["max_vorticity_peak_time"] = float(times[mv_peak_idx])
    case["wall_seconds"] = round(wall, 2)
    case["series"] = series
    print(json.dumps({k: v for k, v in case.items() if k != "series"},
                     indent=2), flush=True)
    print("case wall time %.2f s" % wall, flush=True)
    return case, snap


def case_hash(case):
    """SHA-256 of a case dict with wall-clock fields removed."""
    slim = {k: v for k, v in case.items()
            if k not in ("wall_seconds", "runtime_seconds")}
    blob = json.dumps(slim, sort_keys=True).encode()
    return hashlib.sha256(blob).hexdigest()


def main():
    nu = 0.000125
    dt = 0.01
    cases = []

    # Validation gate for the snapshot loop.
    snapshot_ok = validate_snapshot_loop()

    # Move 1 cost confirmation.
    probe96 = cost_probe_96(nu, dt)

    # Move 1: full 96^3 runs.
    kp96, snap96 = run_case(
        "kida-pelz-type-96^3-nu%.6f" % nu,
        "Kida-Pelz at 96^3, viscosity %s, final time 10.0 (1000 "
        "steps). First full 96^3 run of the lab; Round 6 measured "
        "the cost and Round 3 rejected it with the old solver." % nu,
        kida_pelz, nu, dt, 10.0, n=96, snapshot=snapshot_ok)
    cases.append(kp96)

    tg96, _ = run_case(
        "taylor-green-96^3-nu%.6f" % nu,
        "Taylor-Green at 96^3, viscosity %s, final time 10.0 (1000 "
        "steps)." % nu,
        taylor_green, nu, dt, 10.0, n=96)
    cases.append(tg96)

    # Move 2: longer-time Taylor-Green at 64^3.
    tg64_t20, _ = run_case(
        "taylor-green-64^3-nu%.6f-T20" % nu,
        "Taylor-Green at 64^3, viscosity %s, final time 20.0 (2000 "
        "steps). Round 6 left it still rising at T = 10; this tests "
        "whether it peaks and decays like Kida-Pelz or keeps rising."
        % nu,
        taylor_green, nu, dt, 20.0, n=64)
    cases.append(tg64_t20)

    # Poster snapshot for round 7 (only when the snapshot loop ran).
    poster_meta = None
    if snap96 is not None:
        mid = 96 // 2
        vort_mag = np.sqrt(snap96["ox"] ** 2 + snap96["oy"] ** 2
                           + snap96["oz"] ** 2)
        np.save(os.path.join(POSTER, "kida_peak_vortmag_r7.npy"),
                vort_mag[:, :, mid])
        np.save(os.path.join(POSTER, "kida_peak_u_r7.npy"),
                snap96["u"][:, :, mid])
        np.save(os.path.join(POSTER, "kida_peak_v_r7.npy"),
                snap96["v"][:, :, mid])
        poster_meta = {
            "grid": 96,
            "nu": nu,
            "dt": dt,
            "final_time": 10.0,
            "enstrophy_initial": kp96["enstrophy_initial"],
            "enstrophy_peak": kp96["enstrophy_peak"],
            "enstrophy_growth": kp96["enstrophy_growth_factor"],
            "peak_time": snap96["peak_time"],
            "slice": "z = pi plane, index %d" % mid,
            "max_vorticity_peak_slice": float(vort_mag[:, :, mid].max()),
            "runtime_seconds": kp96["runtime_seconds"],
            "snapshot_loop_validated": True,
        }
        with open(os.path.join(POSTER, "ns_meta_r7.json"), "w") as fh:
            json.dump(poster_meta, fh, indent=2)
        print("poster snapshot saved: kida_peak_*_r7.npy, ns_meta_r7.json",
              flush=True)
    else:
        print("snapshot loop failed validation; no poster snapshot from "
              "this run (render gets its own evolution pass)", flush=True)

    # Resolution scaling: 64^3 (round 6) vs 96^3 (this round).
    scaling = {
        "kida_pelz": {
            "enstrophy_growth_64_round6": 88.24,
            "enstrophy_growth_96_round7":
                kp96["enstrophy_growth_factor"],
            "vorticity_growth_64_round6": 18.52,
            "vorticity_growth_96_round7":
                kp96["max_vorticity_growth_factor"],
            "growth_ratio_96_over_64_enstrophy":
                kp96["enstrophy_growth_factor"] / 88.24,
            "growth_ratio_96_over_64_vorticity":
                kp96["max_vorticity_growth_factor"] / 18.52,
        },
        "taylor_green": {
            "enstrophy_growth_64_round6": 87.56,
            "enstrophy_growth_96_round7":
                tg96["enstrophy_growth_factor"],
            "vorticity_growth_64_round6": 19.14,
            "vorticity_growth_96_round7":
                tg96["max_vorticity_growth_factor"],
            "growth_ratio_96_over_64_enstrophy":
                tg96["enstrophy_growth_factor"] / 87.56,
            "growth_ratio_96_over_64_vorticity":
                tg96["max_vorticity_growth_factor"] / 19.14,
        },
        "note": "Ratio above 1 means growth keeps rising with "
                "resolution; near 1 means it saturates at these "
                "resolutions. Round 6 perturbed Taylor-Green rose "
                "1.35x from 48^3 to 64^3.",
    }

    # Viscosity ladder extended with the 96^3 point.
    ladder = {
        "nu_0.001_round2_64": 18.86,
        "nu_0.0005_round4_64": 40.33,
        "nu_0.00025_round5_64": 64.46,
        "nu_0.000125_round6_64": 88.24,
        "nu_0.000125_round7_96_kida_pelz":
            kp96["enstrophy_growth_factor"],
        "nu_0.000125_round7_96_taylor_green":
            tg96["enstrophy_growth_factor"],
    }

    # Dual run of the strongest case (determinism check).
    best_all = max(cases, key=lambda c: c["max_vorticity_growth_factor"])
    print("strongest case: %s, max vorticity growth %.4f"
          % (best_all["name"], best_all["max_vorticity_growth_factor"]),
          flush=True)
    if best_all["name"].startswith("kida-pelz-type-96"):
        dual_case, _ = run_case(best_all["name"],
                                best_all["description"], kida_pelz,
                                nu, dt, 10.0, n=96,
                                snapshot=snapshot_ok)
    elif best_all["name"].startswith("taylor-green-96"):
        dual_case, _ = run_case(best_all["name"],
                                best_all["description"], taylor_green,
                                nu, dt, 10.0, n=96)
    else:
        dual_case, _ = run_case(best_all["name"],
                                best_all["description"], taylor_green,
                                nu, dt, 20.0, n=64)
    h1 = case_hash(best_all)
    h2 = case_hash(dual_case)
    dual = {
        "case": best_all["name"],
        "first_hash": h1,
        "second_hash": h2,
        "identical": h1 == h2,
        "first_enstrophy_growth":
            best_all["enstrophy_growth_factor"],
        "second_enstrophy_growth":
            dual_case["enstrophy_growth_factor"],
        "first_vorticity_growth":
            best_all["max_vorticity_growth_factor"],
        "second_vorticity_growth":
            dual_case["max_vorticity_growth_factor"],
    }
    print("dual run identical: %s" % dual["identical"], flush=True)

    hunt = {
        "date": "2026-11-21",
        "round": 7,
        "moves": ["full-96-cubed-nu-0.000125", "longer-time-taylor-green"],
        "snapshot_loop_validated": snapshot_ok,
        "protocol": "nu = %.6f, dt = %.3f, pseudo-spectral real-FFT "
                    "solver (compute/navier_stokes_r4.py, verified "
                    "against the reference solver to near machine "
                    "precision in round 4), 2/3 dealiasing, RK4; "
                    "periodic cube [0, 2*pi]^3" % (nu, dt),
        "cases": cases,
        "timing_probe_96_cubed": probe96,
        "resolution_scaling_64_to_96": scaling,
        "viscosity_ladder": ladder,
        "dual_run": dual,
        "poster_snapshot": poster_meta,
        "strongest_signal": {
            "case": best_all["name"],
            "max_vorticity_growth_factor":
                best_all["max_vorticity_growth_factor"],
            "enstrophy_growth_factor":
                best_all["enstrophy_growth_factor"],
            "final_time": best_all["final_time"],
            "stayed_smooth": best_all["stayed_smooth"],
        },
    }
    with open("data/navier_stokes_hunt_r7.json", "w") as fh:
        json.dump(hunt, fh, indent=2)
    print("wrote data/navier_stokes_hunt_r7.json", flush=True)
    return hunt


if __name__ == "__main__":
    main()
