"""Navier-Stokes blowup hunt, round 5.

Lower viscosity: nu = 0.00025, half the round 4 value, at 64^3, same
protocol otherwise (dt = 0.01, final time 10.0, 1000 steps;
pseudo-spectral, 2/3 dealiasing, RK4; periodic cube [0, 2*pi]^3).

Case 1, Kida-Pelz: u = sin x cos y cos z, v = cos x sin y cos z,
w = -2 cos x cos y sin z. Round 4 at nu = 0.0005 gave enstrophy
growth 40.33 and max vorticity growth 14.65 at 64^3, both higher
than round 2 at nu = 0.001 (18.86 and 11.51). Halving the viscosity
again tests whether the growth rises further once viscous damping
is weaker still.

Stability check: same as round 4. A short probe run (Kida-Pelz,
64^3, nu = 0.00025, 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 instead: 64^3, nu = 0.0005, final time 20.0
(the round 4 run extended), same two cases. The fallback decision
is recorded in the output JSON.

Timing check: round 3 rejected 96^3 because the measured cost
exploded. Round 4 at 64^3 cost about 2009 s (Kida-Pelz) and 1421 s
(Taylor-Green) wall. The probe wall time is compared against the
round 4 probe cost; if a single 100-step probe takes more than
about three times the round 4 probe, that is treated as a cost
explosion and the lower-viscosity move is rejected on cost grounds
with the measured evidence.

Solver note: the runs use the real-FFT solver in
compute/navier_stokes_r4.py, unchanged, which was verified against
the reference solver to near machine precision in round 4.

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

import json
import os
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 kida_pelz, summarise  # noqa: E402


def stability_probe(nu, dt):
    """Short Kida-Pelz run to final time 1.0 (100 steps at dt 0.01).

    Returns (stable, probe_result, probe_series, wall_seconds).
    """
    print("stability probe: kida-pelz 64^3, nu = %.5f, 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):
    print("round 5 case: %s at 64^3, nu = %.5f, T = %.1f"
          % (name, nu, final_time), flush=True)
    t0 = time.time()
    u0, v0, w0 = field_fn(64)
    result, series = run_fields_rfft(u0, v0, w0, n=64, 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(case, indent=2), flush=True)
    print("case wall time %.2f s" % wall, flush=True)
    return case


def main():
    nu_low = 0.00025
    nu_fallback = 0.0005
    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 4 probe cost reference: the round 4 probe was a 100-step
    # run of the same solver at the same grid. Its wall time is not
    # stored in the round 4 JSON, so the cost check compares the
    # probe per-step cost against the round 4 full-run per-step
    # cost (2008.89 s / 1000 steps = 2.01 s/step Kida-Pelz,
    # 1421.25 s / 1000 steps = 1.42 s/step Taylor-Green).
    # A probe per-step cost above 3x the round 4 Kida-Pelz
    # per-step cost (6.03 s/step) counts as a cost explosion.
    probe_per_step = probe_wall / 100.0
    cost_exploded = probe_per_step > 6.03

    move = None
    fallback_reason = None
    if not stable:
        move = "fallback-longer-time"
        fallback_reason = ("stability probe failed at nu = 0.00025 "
                           "(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 4 Kida-Pelz per-step cost (6.03 "
                           "s/step); lower viscosity rejected on "
                           "cost grounds" % probe_per_step)
    else:
        move = "lower-viscosity"
        print("probe passed: keeping dt = 0.01, running nu = 0.00025",
              flush=True)

    if move == "lower-viscosity":
        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))

    case1 = run_case(
        "kida-pelz-type-64^3-nu%.5f" % 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 5 rerun at 64^3 with viscosity %s." % nu,
        kida_pelz, nu, dt, ft)
    cases.append(case1)

    case2 = run_case(
        "taylor-green-64^3-nu%.5f" % 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, nu, dt, ft)
    cases.append(case2)

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


if __name__ == "__main__":
    main()
