"""Independent T1 threshold audit. Source model is imported unchanged; no reference read."""
import sys
sys.dont_write_bytecode = True
import hashlib, importlib.util, itertools, json, math, platform, time
from datetime import datetime, timezone
from decimal import Decimal, getcontext
from pathlib import Path
import numpy as np

start = time.perf_counter()
source = Path(__file__).with_name('knot12d.py')
spec = importlib.util.spec_from_file_location('original_knot12d', source)
model = importlib.util.module_from_spec(spec)
spec.loader.exec_module(model)
getcontext().prec = 65
PI = Decimal('3.141592653589793238462643383279502884197169399375105820974944592307816406286')
def sin(x):
    term = total = x
    for n in range(1, 150):
        term *= -x*x / Decimal((2*n)*(2*n+1))
        total += term
        if abs(term) < Decimal('1e-70'):
            break
    return total

sines = {i: sin(PI*Decimal(i)/27)**2 for i in range(1,14)}
def residues(ms, s):
    return tuple(sorted(min((m*s)%27, 27-(m*s)%27) for m in ms))
def gap_for(ms,s):
    return Decimal(4)*sum((sines.get(i,Decimal(0)) for i in residues(ms,s)),Decimal(0))/len(ms)
def gap(ms):
    return min(gap_for(ms,s) for s in range(1,27))

sets = list(itertools.combinations(range(1,14),5))
bestgap = max(gap(ms) for ms in sets)
tied = [ms for ms in sets if abs(gap(ms)-bestgap)<Decimal('1e-55')]
runner_up = max(gap(ms) for ms in sets if ms not in tied)
original_best = max(sets, key=model.station_min_gap)
c = Decimal(2).sqrt()*sin(PI/27)
phases = [('inner',c/(1+c),1,.75),('vertical',c,.75,.25),('outer',c/(1-c),.25,0)]

def around(make, radius, before, after):
    values = []
    for factor, expected in [(1-1e-7,before),(1+1e-7,after)]:
        r = float(radius)*factor
        fraction = model.nearest_fraction(model.dist(make(r)))
        assert abs(fraction-expected)<1e-12, (r,fraction,expected)
        values.append({'r':r,'fraction':fraction})
    return values

out = {'date_utc':datetime.now(timezone.utc).isoformat(), 'source':str(source),
       'sha256':hashlib.sha256(source.read_bytes()).hexdigest(),
       'python':sys.version,'platform':platform.platform(),'numpy':np.__version__,
       'scope':'T1 only; original embedding and nearest_fraction functions, unchanged. No T2-T4 run; no reference present.',
       '3D_transitions':[], 'embeddings':{}, 'optimal_sets':tied,
       'original_float_selected_set':original_best,
       'optimal_gap_minus_runner_up':str(bestgap-runner_up)}
for name,r,before,after in phases:
    out['3D_transitions'].append({'phase':name,'threshold':str(r),'check':around(model.torus3d,r,before,after)})

makers = {'3D':model.torus3d}
for name,ms in [('4D',[1]),('12D-u',[1,5,7,11,13]),('12D-n',[1,2,3,4,5]),('12D-*',list(original_best))]:
    g = gap(ms); r = (g/2).sqrt()
    minimizers = [s for s in range(1,27) if abs(gap_for(ms,s)-g)<Decimal('1e-55')]
    make = lambda r, ms=ms:model.flat(ms,r)
    makers[name]=make
    out['embeddings'][name] = {'multipliers':ms,'station_gap_squared':str(g),'threshold':str(r),
       'minimizing_station_steps':minimizers,'sine_residues':residues(ms,minimizers[0]),
       'check':around(make,r,1,0)}
makers['12D-rnd']=model.random12
for name,make in makers.items():
    rows=[{'r':r,'nearest_fraction':model.nearest_fraction(model.dist(make(r)))} for r in model.R_GRID]
    out['embeddings'].setdefault(name,{})['grid_rows']=rows
    out['embeddings'][name]['first_grid_failure']=next((v['r'] for v in rows if v['nearest_fraction']<1),None)
assert len(tied)==9
assert all(abs(gap(ms)-bestgap)<Decimal('1e-55') for ms in tied)
assert out['embeddings']['12D-rnd']['grid_rows'][0]['nearest_fraction']==1/108
out['elapsed_seconds']=time.perf_counter()-start
Path(__file__).with_name('threshold-audit.json').write_text(json.dumps(out,indent=2)+'\n')
print(json.dumps({k:v for k,v in out.items() if k not in ['embeddings','3D_transitions']},indent=2))
for name,v in out['embeddings'].items():
    print(name, v.get('threshold','no flat threshold'), 'first grid failure',v['first_grid_failure'])
print('All boundary checks passed.')
