"""Navier-Stokes blowup hunt, round 6: deep dive at nu = 0.000125.

Continues the viscosity ladder (nu 0.001 -> 0.0005 -> 0.00025 -> 0.000125)
at 64^3 on the Round 4 real-FFT solver, but this round is a deep dive,
not a repeat: it targets near-critical initial data and measures
scaling, so the outcome is either a candidate blowup profile with
measurable scaling or a quantitative bound on the resolution and time
a singularity would need.

Cases at 64^3, nu = 0.000125, dt = 0.01, T = 10 (1000 steps), unless
noted:
  1. Kida-Pelz (ladder continuation).
  2. Taylor-Green (ladder continuation).
  3. Perturbed Taylor-Green (symmetry-breaking, Round 1's
     second-strongest case at 32^3; the near-critical candidate that
     actually grew in Round 1, unlike the tubes).
  4. Anti-parallel vortex tubes, Round 1 configuration exactly
     (gamma 2.0, core 0.5, separation 1.6, displacement 0.1 sin y):
     the literature-suspected colliding-tube configuration. Rounds 1
     and 2 found it inert (growth about 1.00); repeating it at the new
     viscosity tests whether lower viscosity wakes it up.
  5. Tight anti-parallel tubes (gamma 3.0, core 0.4, separation 1.0,
     displacement 0.2 sin y): a closer, thinner, harder-displaced
     variant toward Kerr's original setup, because the Round 1
     configuration never interacts within T = 10.
  6. Perturbed Taylor-Green at 48^3: resolution scaling of the
     strongest new case (48^3 vs 64^3 growth).
  7. Kida-Pelz at T = 20 (2000 steps): longer-time behaviour at the
     new viscosity, which Round 5 left untested. Tests whether the
     growth is transient or runaway.

Plus a 96^3 cost probe: 10 steps of Kida-Pelz at 96^3 with the Round 4
solver, measuring per-step wall time and peak RSS, extrapolated to a
full 1000-step run. Round 3 rejected 96^3 on measured cost (about
8.8 h) with the OLD reference solver; this probe re-measures with the
current solver and does NOT start a full 96^3 run.

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.

Stability check: same as Round 5. A short probe run (Kida-Pelz,
64^3, nu = 0.000125, dt = 0.01, final time 1.0, 100 steps) runs
first. The probe passes only if all diagnostics stay finite, the
energy does not grow, and the enstrophy peak stays below ten times
its initial value. If the probe fails, lower viscosity is REJECTED
with the measured evidence, and the run falls back to the
longer-time move: 64^3, nu = 0.00025, final time 20.0, same cases.
Cost gate: probe per-step cost above 3x the Round 5 Kida-Pelz
per-step cost (719 s / 1000 steps = 0.719 s/step, limit 2.157 s/step)
counts as a cost explosion and triggers the same fallback.

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

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

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


def stability_probe(nu, dt):
    """Short Kida-Pelz run to final time 1.0 (100 steps at dt 0.01)."""
    print("stability probe: kida-pelz 64^3, nu = %.6f, dt = %.3f, "
          "final time 1.0" % (nu, dt), flush=True)
    t0 = time.time()
    u0, v0, w0 = kida_pelz(64)
    result, series = run_fields_rfft(u0, v0, w0, n=64, nu=nu, dt=dt,
                                     final_time=1.0)
    wall = time.time() - t0
    print("probe wall time %.2f s" % wall, flush=True)
    print(json.dumps(result, indent=2), flush=True)
    finite = result["stayed_smooth"]
    energy_ok = result["energy_final"] <= result["energy_initial"]
    ens_ratio = result["enstrophy_peak"] / result["enstrophy_initial"]
    stable = bool(finite and energy_ok and ens_ratio < 10.0)
    print("probe: finite=%s energy_ok=%s enstrophy_peak/initial=%.3f "
          "stable=%s" % (finite, energy_ok, ens_ratio, stable),
          flush=True)
    return stable, result, series, wall


def run_case(name, description, field_fn, nu, dt, final_time, n=64):
    print("round 6 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)
    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


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 tight_tubes(n):
    """Closer, thinner, harder-displaced anti-parallel tubes."""
    return anti_parallel_tubes(n, gamma=3.0, r0=0.4, sep=0.5, disp=0.2)


def cost_probe_96(nu, dt, steps=10):
    """10 steps of Kida-Pelz at 96^3 with the Round 4 solver.

    Measures per-step wall time and peak RSS, extrapolates a full
    1000-step run. Does NOT run the full 96^3 case.
    """
    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"],
        "note": "Round 3 rejected 96^3 at about 8.8 h with the old "
                "reference solver; this probe re-measures with the "
                "current real-FFT solver. A full 96^3 run was not "
                "started in this round.",
    }
    print(json.dumps(probe, indent=2), flush=True)
    return probe


def main():
    nu_low = 0.000125
    nu_fallback = 0.00025
    dt = 0.01
    final_time = 10.0
    cases = []

    stable, probe_result, _probe_series, probe_wall = stability_probe(
        nu_low, dt)
    probe_record = {
        "nu": nu_low,
        "dt": dt,
        "final_time": 1.0,
        "wall_seconds": round(probe_wall, 2),
        "stayed_smooth": probe_result["stayed_smooth"],
        "energy_initial": probe_result["energy_initial"],
        "energy_final": probe_result["energy_final"],
        "enstrophy_initial": probe_result["enstrophy_initial"],
        "enstrophy_peak": probe_result["enstrophy_peak"],
        "enstrophy_final": probe_result["enstrophy_final"],
        "enstrophy_peak_over_initial":
            probe_result["enstrophy_peak"]
            / probe_result["enstrophy_initial"],
        "max_vorticity_initial": probe_result["max_vorticity_initial"],
        "max_vorticity_peak": probe_result["max_vorticity_peak"],
        "max_vorticity_final": probe_result["max_vorticity_final"],
        "passed": stable,
    }

    # Round 5 Kida-Pelz per-step cost: 719 s / 1000 steps = 0.719 s/step.
    # Above 3x (2.157 s/step) counts as a cost explosion.
    probe_per_step = probe_wall / 100.0
    cost_exploded = probe_per_step > 2.157

    move = None
    fallback_reason = None
    if not stable:
        move = "fallback-longer-time"
        fallback_reason = ("stability probe failed at nu = 0.000125 "
                           "(passed=False); lower viscosity rejected "
                           "with measured probe evidence")
    elif cost_exploded:
        move = "fallback-longer-time"
        fallback_reason = ("probe per-step cost %.2f s exceeds 3x the "
                           "round 5 Kida-Pelz per-step cost (2.157 "
                           "s/step); lower viscosity rejected on "
                           "cost grounds" % probe_per_step)
    else:
        move = "lower-viscosity-deep-dive"
        print("probe passed: keeping dt = 0.01, running nu = 0.000125",
              flush=True)

    if move == "lower-viscosity-deep-dive":
        nu = nu_low
        ft = final_time
    else:
        print("FALLBACK: %s" % fallback_reason, flush=True)
        nu = nu_fallback
        ft = 20.0

    steps = int(round(ft / dt))

    builders = [
        ("kida-pelz-type-64^3-nu%.6f" % nu,
         "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. "
         "Round 6 rerun at 64^3 with viscosity %s." % nu,
         kida_pelz, 64, ft),
        ("taylor-green-64^3-nu%.6f" % nu,
         "Standard Taylor-Green vortex u = sin x cos y cos z, "
         "v = -cos x sin y cos z, w = 0, at 64^3 with viscosity "
         "%s." % nu,
         taylor_green, 64, ft),
        ("perturbed-taylor-green-64^3-nu%.6f" % nu,
         "Taylor-Green plus divergence-free symmetry-breaking mode, "
         "amplitude 0.3, from A_z = 0.15 sin(2x) sin(2y) cos(z). "
         "Round 1 second-strongest case; rerun at 64^3 with "
         "viscosity %s." % nu,
         perturbed_taylor_green, 64, ft),
        ("anti-parallel-vortex-tubes-64^3-nu%.6f" % nu,
         "Two Gaussian vortex tubes of opposite circulation, core "
         "radius 0.5, separation 1.6, centre-lines displaced by "
         "0.1 sin(y); velocity from Fourier Biot-Savart. Round 1 "
         "configuration exactly; rounds 1 and 2 found it inert "
         "(growth about 1.00).",
         anti_parallel_tubes, 64, ft),
        ("tight-anti-parallel-tubes-64^3-nu%.6f" % nu,
         "Anti-parallel vortex tubes, tight variant: gamma 3.0, core "
         "radius 0.4, separation 1.0, displacement 0.2 sin(y); "
         "closer and thinner than the Round 1 configuration, toward "
         "Kerr's original setup.",
         tight_tubes, 64, ft),
        ("perturbed-taylor-green-48^3-nu%.6f" % nu,
         "Perturbed Taylor-Green rerun at 48^3 for resolution "
         "scaling against the 64^3 run.",
         perturbed_taylor_green, 48, ft),
    ]
    for name, desc, fn, n, ftime in builders:
        cases.append(run_case(name, desc, fn, nu, dt, ftime, n=n))

    # Longer-time case at the new viscosity (Round 5 left this untested).
    if move == "lower-viscosity-deep-dive":
        cases.append(run_case(
            "kida-pelz-type-64^3-nu%.6f-T20" % nu,
            "Kida-Pelz at 64^3, viscosity %s, final time 20.0 "
            "(2000 steps). Longer-time behaviour at the new "
            "viscosity." % nu,
            kida_pelz, nu, dt, 20.0, n=64))

    # 96^3 cost probe (measurement only, no full run).
    probe96 = cost_probe_96(nu, dt)

    # Resolution scaling summary for the perturbed Taylor-Green pair.
    ptg64 = next(c for c in cases if c["name"].startswith(
        "perturbed-taylor-green-64"))
    ptg48 = next(c for c in cases if c["name"].startswith(
        "perturbed-taylor-green-48"))
    scaling = {
        "case": "perturbed-taylor-green",
        "enstrophy_growth_48": ptg48["enstrophy_growth_factor"],
        "enstrophy_growth_64": ptg64["enstrophy_growth_factor"],
        "vorticity_growth_48": ptg48["max_vorticity_growth_factor"],
        "vorticity_growth_64": ptg64["max_vorticity_growth_factor"],
        "growth_ratio_64_over_48_enstrophy":
            ptg64["enstrophy_growth_factor"]
            / ptg48["enstrophy_growth_factor"],
        "growth_ratio_64_over_48_vorticity":
            ptg64["max_vorticity_growth_factor"]
            / ptg48["max_vorticity_growth_factor"],
        "note": "Ratio above 1 means growth increases with resolution; "
                "near 1 means the growth saturates at these resolutions.",
    }

    # 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)
    dual = None
    if best_all["name"].endswith("-T20"):
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], kida_pelz, 64, 20.0)
    elif best_all["name"].startswith("kida-pelz"):
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], kida_pelz, 64, ft)
    elif best_all["name"].startswith("taylor-green"):
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], taylor_green, 64, ft)
    elif best_all["name"].startswith("perturbed-taylor-green-64"):
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], perturbed_taylor_green, 64, ft)
    elif best_all["name"].startswith("tight"):
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], tight_tubes, 64, ft)
    else:
        dual_name, dual_fn, dual_n, dual_ft = (
            best_all["name"], anti_parallel_tubes, 64, ft)
    print("dual run of strongest case: %s" % dual_name, flush=True)
    dual_case = run_case(dual_name, best_all["description"], dual_fn,
                         nu, dt, dual_ft, n=dual_n)
    h1 = case_hash(best_all)
    h2 = case_hash(dual_case)
    dual = {
        "case": dual_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)

    # Viscosity ladder across rounds (Kida-Pelz, 64^3).
    ladder = {
        "nu_0.001_round2": 18.86,
        "nu_0.0005_round4": 40.33,
        "nu_0.00025_round5": 64.46,
        "nu_0.000125_round6": next(
            c["enstrophy_growth_factor"] for c in cases
            if c["name"].startswith("kida-pelz-type-64")
            and not c["name"].endswith("-T20")),
    }

    hunt = {
        "date": "2026-11-21",
        "round": 6,
        "move": move,
        "fallback_reason": fallback_reason,
        "stability_probe": probe_record,
        "probe_per_step_seconds": round(probe_per_step, 3),
        "cost_exploded": cost_exploded,
        "protocol": "nu = %.6f, dt = %.3f, final_time = %.1f, "
                    "%d steps; 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; dt chosen after a "
                    "stability probe to final time 1.0 "
                    "(100 steps at dt 0.01, passed=%s)" % (
                        nu, dt, ft, steps, stable),
        "cases": cases,
        "timing_probe_96_cubed": probe96,
        "resolution_scaling": scaling,
        "viscosity_ladder_kida_pelz_64": ladder,
        "dual_run": dual,
        "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_r6.json", "w") as fh:
        json.dump(hunt, fh, indent=2)
    print("wrote data/navier_stokes_hunt_r6.json", flush=True)
    return hunt


if __name__ == "__main__":
    main()
