"""Kickoff 08: exhaustive exact spacing ties and unchanged imported dynamics.

Usage: python curve.py [--source ../knot12d/knot12d.py]
Requires NumPy and Matplotlib. Run beside the frozen predictions.md.
Tie equality is in Z[z]/(z^18+z^9+1), z=exp(2*pi*i/27).
Ordering uses rigorously outward-rounded integer intervals, scale 10^100.
No other result file is read. This script does not execute the source's main.
"""
import argparse
from datetime import datetime, timezone
from decimal import Decimal, localcontext
import hashlib
import importlib.util
import itertools
import json
import math
import os
from pathlib import Path
import platform
import resource
import sys
import time

HERE = Path(__file__).resolve().parent
os.environ.setdefault("MPLCONFIGDIR", str(HERE / ".matplotlib-cache"))
SOURCE_SHA = "0747da40871a4135ee0e29507609d09edf8b5737722c690514ac9a63576813f6"
Q = 10**100


def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def ceildiv(a, b):
    return -((-a)//b)


def atan_inverse(q, terms=100):
    """Bounds scaled by Q, using alternating rational series and its remainder."""
    lo = hi = 0
    for k in range(terms):
        denominator = (2*k+1)*q**(2*k+1)
        low, high = Q//denominator, ceildiv(Q, denominator)
        if k % 2:
            lo -= high
            hi -= low
        else:
            lo += low
            hi += high
    tail = ceildiv(Q, (2*terms+1)*q**(2*terms+1))
    return lo-tail, hi+tail


def cosine_bounds(k, pi_bounds):
    """Certified cos(2*pi*k/27), via positive-term interval recurrence."""
    k = min(k % 27, (-k) % 27)
    if k == 0:
        return Q, Q
    xl = 2*k*pi_bounds[0]//27
    xh = ceildiv(2*k*pi_bounds[1], 27)
    assert 0 < xl <= xh < 4*Q
    x2l, x2h = xl*xl//Q, ceildiv(xh*xh, Q)
    tl = th = low = high = Q
    for n in range(1, 101):
        denominator = Q*(2*n-1)*(2*n)
        tl, th = tl*x2l//denominator, ceildiv(th*x2h, denominator)
        if n % 2:
            low -= th
            high -= tl
        else:
            low += tl
            high += th
    # Taylor polynomial through degree 201 (the odd term is zero).
    remainder = ceildiv(Q*4**202, math.factorial(202))
    return low-remainder, high+remainder


def monomial(k):
    k %= 27
    p = [0]*18
    if k < 18:
        p[k] = 1
    else:
        p[k-9] = p[k-18] = -1
    return tuple(p)


def gap_atom(k):
    a, b = monomial(k), monomial(-k)
    return tuple((2 if i == 0 else 0)-a[i]-b[i] for i in range(18))


def compare(a, b):
    """Items have exact polynomial and integer interval at common scale."""
    if a[0] == b[0]:
        return 0
    if a[2] < b[1]:
        return -1
    if b[2] < a[1]:
        return 1
    raise ArithmeticError("Distinct cyclotomic values have overlapping intervals; increase precision")


def decimal_value(n, denominator):
    with localcontext() as ctx:
        ctx.prec = 90
        return str(Decimal(n)/Decimal(denominator))


def make_geometry():
    a, b = atan_inverse(5), atan_inverse(239)
    pi_bounds = (16*a[0]-4*b[1], 16*a[1]-4*b[0])
    assert 3*Q < pi_bounds[0] < pi_bounds[1] < 4*Q
    cosines = [cosine_bounds(k, pi_bounds) for k in range(27)]
    atoms = {}
    for m in range(1, 14):
        for s in range(1, 14):
            lo, hi = cosines[(m*s) % 27]
            atoms[m, s] = gap_atom(m*s), 2*Q-2*hi, 2*Q-2*lo
    rows, total = [], 0
    for L in range(1, 14):
        best = None
        tied = []
        minimum_steps = {}
        count = 0
        for ms in itertools.combinations(range(1, 14), L):
            count += 1
            smallest = None
            steps = []
            for s in range(1, 14):
                terms = [atoms[m, s] for m in ms]
                value = (tuple(sum(t[0][j] for t in terms) for j in range(18)),
                         sum(t[1] for t in terms), sum(t[2] for t in terms))
                order = -1 if smallest is None else compare(value, smallest)
                if order < 0:
                    smallest, steps = value, [s, 27-s]
                elif order == 0:
                    steps.extend([s, 27-s])
            order = 1 if best is None else compare(smallest, best)
            if order > 0:
                best, tied, minimum_steps = smallest, [ms], {ms: sorted(steps)}
            elif order == 0:
                tied.append(ms)
                minimum_steps[ms] = sorted(steps)
        assert count == math.comb(13, L)
        total += count
        remaining = set(tied)
        orbits = []
        units = [u for u in range(1, 27) if math.gcd(u, 27) == 1]
        while remaining:
            seed = min(remaining)
            orbit = {tuple(sorted(min(m*u % 27, (-m*u) % 27) for m in seed)) for u in units}
            assert orbit <= set(tied)
            remaining -= orbit
            orbits.append(sorted(orbit))
        representative = min(tied)
        poly, lo, hi = best
        with localcontext() as ctx:
            ctx.prec = 90
            gap = Decimal(lo+hi)/Decimal(2*Q*L)
            threshold = (gap/2).sqrt()
        rational = not any(poly[1:])
        rows.append({
            "L": L, "dimension": 2*L+2, "subsets_searched": count,
            "gap": float(gap), "gap_decimal": str(gap), "r_star": float(threshold),
            "r_star_decimal": str(threshold),
            "exact_gap": {"z_definition": "exp(2*pi*i/27)",
                          "minimal_polynomial": "z^18+z^9+1",
                          "numerator_coefficients_ascending": list(poly), "denominator": L},
            "exact_r_star": "sqrt(exact_gap/2)",
            "gap_is_rational": rational,
            "gap_interval_scaled": {"lower": str(lo), "upper": str(hi), "denominator": str(Q*L)},
            "ties": len(tied), "representative": list(representative),
            "minimizing_station_steps": minimum_steps[representative],
            "tied_sets": [list(ms) for ms in tied],
            "orbits": [{"representative": list(orbit[0]), "size": len(orbit),
                        "sets": [list(ms) for ms in orbit]} for orbit in orbits],
        })
        print(f"L={L:2d} gap={gap:.12f} r*={threshold:.12f} ties={len(tied)} orbits={len(orbits)} rep={representative}", flush=True)
    assert total == 8191
    return rows, {"subsets_searched": total, "scale": str(Q),
                  "pi_interval_scaled": [str(x) for x in pi_bounds],
                  "method": "Machin pi identity, outward-rounded integer Taylor intervals; exact equality modulo Phi_27"}


def compare_rows(a, b):
    pa = tuple(v*b["L"] for v in a["exact_gap"]["numerator_coefficients_ascending"])
    pb = tuple(v*a["L"] for v in b["exact_gap"]["numerator_coefficients_ascending"])
    ia, ib = a["gap_interval_scaled"], b["gap_interval_scaled"]
    return compare((pa, int(ia["lower"])*b["L"], int(ia["upper"])*b["L"]),
                   (pb, int(ib["lower"])*a["L"], int(ib["upper"])*a["L"]))


def assess(rows):
    first, last, near = rows[0], rows[-1], rows[-2]
    rational = lambda r, a, b: r["exact_gap"]["numerator_coefficients_ascending"][0]*b == a*r["L"] and not any(r["exact_gap"]["numerator_coefficients_ascending"][1:])
    checks = {}
    checks["E1"] = first["exact_gap"]["numerator_coefficients_ascending"] == list(gap_atom(1)) and first["ties"] == 9
    checks["E2"] = rational(last, 27, 13) and last["ties"] == 1 and len(last["minimizing_station_steps"]) == 26
    drops = [{"from_L": a["L"], "to_L": b["L"], "from_r": a["r_star"], "to_r": b["r_star"]} for a, b in zip(rows, rows[1:]) if compare_rows(a,b)>0]
    checks["S1"] = not drops
    checks["S2"] = 0.88 < rows[4]["r_star"] < 0.90 and compare_rows(rows[4],rows[5])<0 and compare_rows(rows[4],rows[6])<0
    checks["T1"] = near["ties"] == 1 and near["representative"] == [m for m in range(1,14) if m != 9] and rational(near,2,1)
    checks["T2"] = all(len(row["orbits"])==1 and row["ties"] in [1,3,9] for row in rows[1:11])
    checks["D1"] = all(row["dynamics"]["0.14"]["first_pass"] >= 0.95 for row in rows[1:])
    checks["D2"] = all(row["dynamics"]["0.30"]["transfer"]>=0.95 and row["dynamics"]["0.30"]["stay"]>=0.85 for row in rows[4:])
    stay_increases = []
    for row in rows:
        for a,b in [("0.30","0.50"),("0.50","0.70")]:
            va,vb=row["dynamics"][a]["stay"],row["dynamics"][b]["stay"]
            if vb-va>1e-8:stay_increases.append({"L":row["L"],"from_r":a,"to_r":b,"from_stay":va,"to_stay":vb})
    checks["D3"] = not stay_increases
    transfer_drops=[{"from_L":a["L"],"to_L":b["L"],"from_transfer":a["dynamics"]["0.70"]["transfer"],"to_transfer":b["dynamics"]["0.70"]["transfer"]} for a,b in zip(rows,rows[1:]) if a["dynamics"]["0.70"]["transfer"]-b["dynamics"]["0.70"]["transfer"]>1e-6]
    checks["D4"] = bool(transfer_drops)
    return {k:"HELD" if v else "FAILED" for k,v in checks.items()}, {"threshold_decreases":drops,"stay_increases_with_radius":stay_increases,"transfer_decreases_at_r070":transfer_drops}


def make_plot(rows):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(figsize=(10, 5.6), layout="constrained")
    fig.set_facecolor("#fbfaf7")
    ax.set_facecolor("#fbfaf7")
    x=[r["dimension"] for r in rows];y=[r["r_star"] for r in rows]
    ax.plot(x,y,"o-",lw=2,color="#176b83",label="Best subset at each dimension")
    for a,b in zip(rows,rows[1:]):
        if compare_rows(a,b)>0:
            ax.plot([a["dimension"],b["dimension"]],[a["r_star"],b["r_star"]],color="#c54537",lw=3)
    ax.scatter([12],[rows[4]["r_star"]],s=125,facecolors="none",edgecolors="#925ba5",linewidths=2,zorder=5,label="12D example")
    ax.axhline(0.141,color="#8b694b",linestyle="--",linewidth=1.3,label="3D reference from kickoff: 0.141")
    ax.axhline(math.sqrt(27/26),color="#68715d",linestyle=":",linewidth=1.5,label="Simplex ceiling: sqrt(27/26)")
    ax.set_xticks(x);ax.set_xlim(3.5,28.5);ax.set_ylim(0.08,1.10)
    ax.set_xlabel("Active dimension, 2L + 2");ax.set_ylabel("Crowding threshold r*")
    ax.set_title("The complete optimized spacing curve",loc="left",fontweight="bold",pad=15)
    ax.grid(axis="y",alpha=0.18);ax.spines[["top","right"]].set_visible(False)
    ax.legend(loc="lower right",frameon=False,fontsize=9)
    fig.savefig(HERE/"curve.png",dpi=180,metadata={"Description":"Exhaustive subsets with exact cyclotomic ties; straight segments only"})
    plt.close(fig)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source",type=Path,default=HERE.parent/"knot12d"/"knot12d.py")
    args=parser.parse_args()
    start=time.monotonic_ns();started=datetime.now(timezone.utc).isoformat()
    assert sha(args.source)==SOURCE_SHA,"Source script hash mismatch"
    prediction_sha=sha(HERE/"predictions.md")
    assert (HERE/"predictions.sha256").read_text().split()[0]==prediction_sha,"Frozen prediction hash mismatch"
    spec=importlib.util.spec_from_file_location("kickoff08_source",args.source)
    source=importlib.util.module_from_spec(spec);spec.loader.exec_module(source)
    flat,dist,nearest_fraction,couplings,dynamics = source.flat,source.dist,source.nearest_fraction,source.couplings,source.dynamics
    import numpy as np
    import matplotlib
    rows,exact_method=make_geometry()
    geometry_end=time.monotonic_ns()
    for row in rows:
        ms=row["representative"];rstar=row["r_star"]
        row["threshold_nearest_checks"]={}
        for tag,r in [("below",rstar*(1-1e-6)),("above",rstar*(1+1e-6))]:
            fraction=nearest_fraction(dist(flat(ms,r)))
            row["threshold_nearest_checks"][tag]=fraction
            assert fraction==(1.0 if tag=="below" else 0.0)
        row["dynamics"]={}
        for r in [0.30,0.50,0.70,0.14]:
            X=flat(ms,r);D=dist(X)
            assert X.shape==(108,max(12,row["dimension"]))
            # Translation invariance, checked directly without changing dynamics.
            circulant_error=max(float(np.max(np.abs(D[j]-np.roll(D[0],j)))) for j in range(108))
            assert circulant_error<1e-11
            transfer,first,stay=dynamics(couplings(D,6))
            assert all(-1e-9<=v<=1+1e-9 for v in [transfer,first,stay])
            row["dynamics"][f"{r:.2f}"]={"transfer":transfer,"first_pass":first,"stay":stay,
                                            "nearest_fraction":nearest_fraction(D),"circulant_distance_max_error":circulant_error}
        print(f"dynamics done: L={row['L']} representative={ms}",flush=True)
    dynamics_end=time.monotonic_ns()
    assessments,features=assess(rows)
    make_plot(rows)
    end=time.monotonic_ns()
    assert sha(args.source)==SOURCE_SHA and sha(HERE/"predictions.md")==prediction_sha
    out={"kickoff":"08","started_utc":started,"finished_utc":datetime.now(timezone.utc).isoformat(),
         "source_sha256":SOURCE_SHA,"curve_script_sha256":sha(__file__),"predictions_sha256":prediction_sha,
         "plot_sha256":sha(HERE/"curve.png"),"source_unchanged":True,"predictions_unchanged":True,
         "environment":{"python":sys.version,"platform":platform.platform(),"machine":platform.machine(),
                        "numpy":np.__version__,"matplotlib":matplotlib.__version__,"logical_cpu_count":os.cpu_count(),
                        "numpy_config":np.__config__.show(mode="dicts")},
         "timing_nanoseconds":{"geometry_including_imports":geometry_end-start,"dynamics":dynamics_end-geometry_end,
                                "plot_and_assessment":end-dynamics_end,"wall_through_plot":end-start},
         "peak_rss_native_units":resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
         "peak_rss_units":"bytes on macOS; KiB on Linux",
         "exact_comparison":exact_method,"representative_rule":"lexicographically first exactly tied set",
         "dynamics_definition":{"alpha":6,"tmax":40,"steps":4001,"dt":"0.01","first_pass_tmax":"2.5",
                                "probabilities":"sampled extrema, not continuous-time extrema"},
         "three_dimensional_reference":{"value":0.141,"source":"supplied kickoff; not recomputed"},
         "simplex_gap_exact":"27/13","simplex_threshold_exact":"sqrt(27/26)",
         "prediction_assessments":assessments,"features":features,"rows":rows}
    (HERE/"curve.json").write_text(json.dumps(out,indent=2)+"\n")
    print(json.dumps({"predictions":assessments,"features":features,"wall_nanoseconds":end-start}),flush=True)


if __name__=="__main__":
    main()
