"""Independent stress test around freely viewable Kevin Li (5,41) reference data.
Input: 41 rows of five comma-separated coordinates or a JSON array of rows.
Does not write or redistribute the source or derivative coordinates.
Usage: place search.py and polish.py adjacent and run
python reference-check.py REFERENCE.csv --output reference-check-summary.json
"""
import argparse
import json
import math
from pathlib import Path
from polish import normalize, pair_cost, solve_contacts, smooth_search, np

def score(p):
    return math.degrees(math.acos(float(pair_cost(normalize(p)).max())))

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source",type=Path)
    parser.add_argument("--output",type=Path,default=Path("reference-check-summary.json"))
    args=parser.parse_args()
    source = args.source.read_text().strip()
    rows = json.loads(source) if source.startswith("[") else [line.split(",") for line in source.splitlines() if line.strip()]
    coords = np.asarray(rows, dtype=float)
    if coords.shape != (41, 5) or not np.isfinite(coords).all() or np.any(np.linalg.norm(coords, axis=1) == 0):
        raise ValueError("Expected 41 finite, nonzero five-dimensional directions.")
    center = normalize(coords)
    rng=np.random.default_rng(410502)
    trials=[]
    for noise in [0,1e-7,1e-5,.0001,.001,.004,.012,.03,.07,.12]:
        x=normalize(center+rng.normal(0,noise,center.shape))
        if noise>=.012:
            x=smooth_search(x,[(80,160),(480,210),(1500,180)])
        before=score(x)
        sol,steps=solve_contacts(x)
        trials.append(dict(noise=noise,before_angle_deg=before,after_angle_deg=score(sol),lp_iterations=steps))
    base=score(center)
    record=dict(reference="https://spherical-codes.org/data/5/41",author="Kevin Li (2026)",seed=410502,
                trials=trials,unperturbed_reference_angle_deg=base,
                best_after_LP_angle_deg=max(t['after_angle_deg'] for t in trials),
                significant_improvement=any(t['after_angle_deg']>base+1e-7 for t in trials),
                tolerance_deg=1e-7,coordinates_redistributed=False)
    args.output.write_text(json.dumps(record,indent=2)+"\n")
    print(json.dumps(record,indent=2))
if __name__=="__main__":
    main()
