#!/usr/bin/env python3
"""Reproduce the contact-focused search: save search.py and candidate.json alongside
this file, install NumPy and SciPy, and run python polish.py --output DIRECTORY.
This searches from independent, perturbed D5, and numerical continuation starts.
No published 41-point coordinates are used.
"""
import os
for key in ("OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "OMP_NUM_THREADS"):
    os.environ[key] = "1"
import argparse
import json
import math
import time
from pathlib import Path

import numpy as np
from scipy.optimize import linprog
from scipy.sparse import coo_matrix

from search import COUNT, DIMENSION, ROWS, COLS, roots, normalize, smooth_search, measurements

BASE = Path(__file__).resolve().parent
SEED = 20261124
BENCHMARK_COS = 0.514705973641


def pair_cost(p):
    return (p @ p.T)[ROWS, COLS]


def solve_contacts(p):
    """Sequential minimax LP in local tangent coordinates with trust-region acceptance."""
    p = normalize(p)
    radius = .02
    objective = np.zeros(COUNT * DIMENSION + 1)
    objective[-1] = 1
    dims = np.arange(DIMENSION)
    eq_rows = np.repeat(np.arange(COUNT), DIMENSION)
    eq_cols = np.arange(COUNT * DIMENSION)
    for step in range(32):
        dots = pair_cost(p)
        worst = float(dots.max())
        active = dots > worst - max(.014, 6 * radius)
        first, second, selected = ROWS[active], COLS[active], dots[active]
        rows = np.arange(len(selected))
        # A pair's first-order dot change: v_i·x_j + v_j·x_i.
        row_grid = np.repeat(rows, DIMENSION)
        columns = np.r_[(first[:, None] * DIMENSION + dims).ravel(),
                        (second[:, None] * DIMENSION + dims).ravel(),
                        np.full(len(rows), len(objective) - 1)]
        values = np.r_[p[second].ravel(), p[first].ravel(), -np.ones(len(rows))]
        inequalities = coo_matrix((values, (np.r_[row_grid, row_grid, rows], columns)),
                                  shape=(len(rows), len(objective))).tocsr()
        tangent = coo_matrix((p.ravel(), (eq_rows, eq_cols)),
                             shape=(COUNT, len(objective))).tocsr()
        lp = linprog(objective, A_ub=inequalities, b_ub=worst-selected,
                     A_eq=tangent, b_eq=np.zeros(COUNT),
                     bounds=[(-radius, radius)] * (len(objective)-1) + [(None,None)],
                     method="highs")
        if not lp.success:
            radius *= .35
        else:
            delta = lp.x[:-1].reshape(COUNT, DIMENSION)
            moved = normalize(p + delta)
            improvement = worst - float(pair_cost(moved).max())
            if improvement > 1e-12:
                p = moved
                if improvement >= .35 * max(0, -lp.fun):
                    radius = min(.05, radius * 1.5)
            else:
                radius *= .3
        if radius < .000002:
            break
    return p, step+1


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--output", type=Path, default=Path("."))
    ap.add_argument("--trials", type=int, default=36)
    args = ap.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(SEED)
    raw = json.loads((BASE / "candidate.json").read_text())
    initial = normalize(np.array(raw['directions'], dtype=float))
    elite = []
    history = []
    start = time.perf_counter()
    benchmark = math.degrees(math.acos(BENCHMARK_COS))
    for i in range(args.trials):
        if i == 0:
            p = initial
            tag = "saved local candidate from initial 54-run search"
        elif i % 4 == 1:
            p = rng.normal(size=(COUNT, DIMENSION))
            tag = "fresh random"
        elif i % 4 == 2:
            p = rng.normal(size=(COUNT, DIMENSION))
            p[:40] = roots() + rng.normal(scale=.15, size=(40,DIMENSION))
            tag = "perturbed D5 plus insertion"
        else:
            _, trial, previous = elite[int(rng.integers(len(elite)))]
            scale = float(rng.choice([.04,.08,.15,.21]))
            p = previous + rng.normal(scale=scale, size=previous.shape)
            tag = f"perturb local trial {trial} at {scale:.2f}"
        if i:
            p = smooth_search(p, [(40,170), (180,180), (1100,200)])
        start_angle = math.degrees(math.acos(float(pair_cost(p).max())))
        p, steps = solve_contacts(p)
        rays, exact = measurements(p)
        history.append(dict(trial=i, source=tag, before_LP_angle_deg=start_angle,
                            LP_iterations=steps, **exact))
        elite.append((exact['minimum_angle_deg'], i, p.copy()))
        elite.sort(key=lambda entry: entry[0], reverse=True)
        elite=elite[:5]
        if i%6==0 or i==args.trials-1:
            print(f'{i+1} starts: best {elite[0][0]:.9f}°; elapsed {time.perf_counter()-start:.1f}s',flush=True)
    angle, winner, best = elite[0]
    rays, exact = measurements(best)
    result = dict(seed=SEED, starts=args.trials, previous_search_seed=574,
                  winning_trial=winner, **exact,
                  degree_gap_to_packing=60-angle, comparison_cos=BENCHMARK_COS,
                  comparison_min_angle_deg=benchmark, degree_gap_to_comparison=benchmark-angle,
                  comparison_source="https://spherical-codes.org/ (5,41), Kevin Li, 2026",
                  method="Independent and local continuation starts, smooth warm-up, then tangent-space minimax LP with exact normalization and trust-region acceptance. Integer rays rounded at scale 100,000,000. No published coordinates used as inputs.",
                  runtime_seconds=round(time.perf_counter()-start,3), trials=history)
    (args.output/'refined.json').write_text(json.dumps(dict(dimension=5,directions=rays,
        description=f"Highest minimum angle among {args.trials} trials of the local tangent-LP search."),separators=(',',':'))+'\n')
    (args.output/'polish-summary.json').write_text(json.dumps(result,indent=2)+'\n')


if __name__ == '__main__':
    main()
