"""Navier-Stokes blowup hunt: stress cases beyond Taylor-Green.

Case 1, perturbed Taylor-Green: Taylor-Green plus a divergence-free
symmetry-breaking perturbation built from the vector potential
A_z = a sin(2x) sin(2y) cos(z) with a = 0.15, giving a perturbation
velocity of amplitude 0.3. The perturbation breaks the discrete
symmetries that keep Taylor-Green in a symmetric subspace.

Case 2, anti-parallel vortex tubes: two Gaussian vortex tubes parallel
to the y axis, centred at x = pi - 0.8 and x = pi + 0.8, z = pi, core
radius 0.5, opposite circulation, with centre-lines displaced in
opposite directions by 0.1 sin(y) to seed the Crow instability. The
velocity is recovered from the vorticity by the Fourier Biot-Savart
law, u_hat = i k x omega_hat / |k|^2. This is the colliding-tube
configuration known for strong vortex stretching.

Case 3, Kida-Pelz type high-symmetry flow: the explicit initial field
  u = sin(x) cos(y) cos(z)
  v = cos(x) sin(y) cos(z)
  w = -2 cos(x) cos(y) sin(z)
which is divergence free and is the high-symmetry initial condition
used in enstrophy-growth studies. Stated here by formula, so the run
is defined by the formula rather than by the name.

All hunt cases use nu = 0.001, ten times smaller than the Taylor-Green
validation run, to weaken viscous damping and stress singularity
formation. The strongest 32^3 case is then rerun at 48^3.

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

import json
import sys
import time

import numpy as np

sys.path.insert(0, "compute")
from navier_stokes import (  # noqa: E402
    build_wavenumbers,
    project_divergence_free,
    run_fields,
    taylor_green,
)


def perturbed_taylor_green(n, a=0.15):
    u0, v0, w0 = taylor_green(n)
    x = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
    xx, yy, zz = np.meshgrid(x, x, x, indexing="ij")
    up = 2.0 * a * np.sin(2.0 * xx) * np.cos(2.0 * yy) * np.cos(zz)
    vp = -2.0 * a * np.cos(2.0 * xx) * np.sin(2.0 * yy) * np.cos(zz)
    return u0 + up, v0 + vp, w0


def anti_parallel_tubes(n, gamma=2.0, r0=0.5, sep=0.8, disp=0.1):
    x = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
    xx, yy, zz = np.meshgrid(x, x, x, indexing="ij")
    dx1 = xx - (np.pi - sep) - disp * np.sin(yy)
    dx2 = xx - (np.pi + sep) + disp * np.sin(yy)
    dz = zz - np.pi
    # Periodic wrap of the separations so the Gaussians see the torus.
    dx1 = (dx1 + np.pi) % (2.0 * np.pi) - np.pi
    dx2 = (dx2 + np.pi) % (2.0 * np.pi) - np.pi
    dz = (dz + np.pi) % (2.0 * np.pi) - np.pi
    oy = gamma * np.exp(-(dx1**2 + dz**2) / r0**2) \
        - gamma * np.exp(-(dx2**2 + dz**2) / r0**2)
    ox = np.zeros_like(oy)
    oz = np.zeros_like(oy)
    kx, ky, kz = build_wavenumbers(n)
    k2 = kx**2 + ky**2 + kz**2
    k2_safe = np.where(k2 == 0, 1.0, k2)
    oxh = np.fft.fftn(ox)
    oyh = np.fft.fftn(oy)
    ozh = np.fft.fftn(oz)
    # u_hat = i k x omega_hat / |k|^2, zero mode set to zero.
    uhx = 1j * (ky * ozh - kz * oyh) / k2_safe
    uhy = 1j * (kz * oxh - kx * ozh) / k2_safe
    uhz = 1j * (kx * oyh - ky * oxh) / k2_safe
    uhx = np.where(k2 == 0, 0.0, uhx)
    uhy = np.where(k2 == 0, 0.0, uhy)
    uhz = np.where(k2 == 0, 0.0, uhz)
    u0 = np.fft.ifftn(uhx).real
    v0 = np.fft.ifftn(uhy).real
    w0 = np.fft.ifftn(uhz).real
    return u0, v0, w0


def kida_pelz(n):
    x = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
    xx, yy, zz = np.meshgrid(x, x, x, indexing="ij")
    u0 = np.sin(xx) * np.cos(yy) * np.cos(zz)
    v0 = np.cos(xx) * np.sin(yy) * np.cos(zz)
    w0 = -2.0 * np.cos(xx) * np.cos(yy) * np.sin(zz)
    return u0, v0, w0


def summarise(name, description, result):
    return {
        "name": name,
        "description": description,
        "grid": result["grid"],
        "viscosity": result["viscosity"],
        "dt": result["dt"],
        "final_time": result["final_time"],
        "steps": result["steps"],
        "runtime_seconds": result["runtime_seconds"],
        "enstrophy_initial": result["enstrophy_initial"],
        "enstrophy_final": result["enstrophy_final"],
        "enstrophy_peak": result["enstrophy_peak"],
        "enstrophy_growth_factor": result["enstrophy_peak"]
        / result["enstrophy_initial"],
        "max_vorticity_initial": result["max_vorticity_initial"],
        "max_vorticity_final": result["max_vorticity_final"],
        "max_vorticity_peak": result["max_vorticity_peak"],
        "max_vorticity_growth_factor": result["max_vorticity_peak"]
        / result["max_vorticity_initial"],
        "energy_initial": result["energy_initial"],
        "energy_final": result["energy_final"],
        "stayed_smooth": result["stayed_smooth"],
    }


def main():
    nu = 0.001
    dt = 0.01
    final_time = 10.0
    cases = []
    builders = [
        ("perturbed-taylor-green",
         "Taylor-Green plus divergence-free symmetry-breaking mode, "
         "amplitude 0.3, from A_z = 0.15 sin(2x) sin(2y) cos(z).",
         perturbed_taylor_green),
        ("anti-parallel-vortex-tubes",
         "Two Gaussian vortex tubes of opposite circulation, core radius "
         "0.5, separation 1.6, centre-lines displaced by 0.1 sin(y) in "
         "opposite directions; velocity from Fourier Biot-Savart.",
         anti_parallel_tubes),
        ("kida-pelz-type",
         "High-symmetry field u = sin x cos y cos z, "
         "v = cos x sin y cos z, w = -2 cos x cos y sin z.",
         kida_pelz),
    ]
    for name, description, builder in builders:
        print("running %s ..." % name, flush=True)
        u0, v0, w0 = builder(32)
        result, _series = run_fields(u0, v0, w0, n=32, nu=nu, dt=dt,
                                     final_time=final_time)
        case = summarise(name, description, result)
        cases.append(case)
        print(json.dumps(case, indent=2), flush=True)

    best = max(cases, key=lambda c: c["max_vorticity_growth_factor"])
    print("strongest 32^3 case: %s, max vorticity growth factor %.4f"
          % (best["name"], best["max_vorticity_growth_factor"]), flush=True)
    print("rerunning %s at 48^3 ..." % best["name"], flush=True)
    builder = dict((n, b) for n, _d, b in builders)[best["name"]]
    u0, v0, w0 = builder(48)
    result48, _s48 = run_fields(u0, v0, w0, n=48, nu=nu, dt=dt,
                                final_time=final_time)
    case48 = summarise(best["name"] + "-48^3",
                       best["description"] + " Rerun at 48^3.",
                       result48)
    cases.append(case48)
    print(json.dumps(case48, indent=2), flush=True)

    best_all = max(cases, key=lambda c: c["max_vorticity_growth_factor"])
    hunt = {
        "date": "2026-11-20",
        "cases": cases,
        "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.json", "w") as fh:
        json.dump(hunt, fh, indent=2)
    print("wrote data/navier_stokes_hunt.json", flush=True)
    return hunt


if __name__ == "__main__":
    main()
