"""Generate the reference period-doubled orbit at the fixed evidence delay."""
import json, os, numpy as np
from bif_common import (M, fundamentality_gap, dde_residual, richardson_multiplier,
                        spectral_tail)
from find_cascade import capture_doubled, polish, upsample

TAU_EV = 14.0
OUT = os.path.join(os.path.dirname(__file__), "..", "reference_outputs")

x512, T2, alt = capture_doubled(TAU_EV, print)
x512 = np.roll(x512, -int(np.argmax(x512)))
xc, Tc, rc = polish(512, x512, T2, TAU_EV)
xf, Tf, rf = polish(M, upsample(xc, M), Tc, TAU_EV, max_nfev=30000)
mu, _, canary, spread = richardson_multiplier(xf, Tf, TAU_EV)
info = {"tau_evidence": TAU_EV, "period2": Tf, "resid_linf": rf,
        "fundamentality_gap": fundamentality_gap(xf, Tf),
        "spectral_tail": spectral_tail(xf),
        "amplitude": float(xf.max() - xf.min()), "min_x": float(xf.min()),
        "mu_re": float(mu.real), "period_ratio_vs_T1_at_tau_ev": None}
np.savez(os.path.join(OUT, "doubled_orbit.npz"), tau=TAU_EV, period=Tf, x=xf)
print(json.dumps(info, indent=2))
with open(os.path.join(OUT, "doubled_orbit_report.json"), "w") as fh:
    json.dump(info, fh, indent=2)
