"""Validate and control the independent Dirichlet-spectrum comparison records.
Run in Sage with generate.py, both checkpoint JSONs and KnotInfo inputs.
The spectrum's 212-bit values are numerical checks, not certified inputs for
this table. A conservative 1e-30 comparison tolerance and 1e-25 cutoff
separation are explicit. The legacy kernel's extra 0.001 cutoff margin is
handled by testing each returned candidate rather than trusting list length.
"""
import numberdb.sage as numberdb
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.rational_field import QQ
from fractions import Fraction
from generate import ROOT,KNOTS,load_checkpoints,from_endpoints
import json,copy
R=RealIntervalField(600)
p=load_checkpoints();primary={(r['n'],r['k']):r for r in p['knots']}
l=json.loads((ROOT/'legacy-checkpoints.json').read_text());rows={(r['n'],r['k']):r for r in l['knots']}
assert set(primary)==set(KNOTS)==set(rows)

def valid(r):
 try:
  key=(r['n'],r['k']);cut=R(QQ(Fraction(r['cutoff'])));found=[]
  for g in r['legacy_spectrum']:
   x=R(QQ(Fraction(g['real'])))
   if not (x.lower()>0 and x.upper()<10**6 and abs(x-cut).lower()>QQ(1)/10**25):return False
   below=bool(x.upper()<cut.lower())
   if below!=g['below_cutoff']:return False
   if below:found.extend([x]*int(g['multiplicity']))
  found.sort(key=lambda x:x.center())
  expected_count=0
  for witness in primary[key]['witnesses']:
   enclosure=from_endpoints(witness['real'],R)
   if enclosure.upper()<cut.lower():expected_count+=1
   elif not enclosure.lower()>cut.upper():return False
  if len(found)!=expected_count or expected_count!=r['expected_count_below_cutoff'] or len(found)<4:return False
  for j in range(4):
   expected=from_endpoints(primary[key]['values'][j],R)
   if abs(found[j]-expected).upper()>=QQ(1)/10**30:return False
  return True
 except Exception:return False
failures=[{'n':r['n'],'k':r['k'],'issue':'legacy rank/count/cutoff mismatch'} for r in rows.values() if not valid(r)]
# Published SnapPy/paper figure-eight systole gives a nonzero known answer.
first=rows[4,1]['legacy_spectrum'][0]['real'];known=(R(QQ(Fraction(first))) in R('1.08707014499','1.08707014500')) and valid(rows[9,7])
bad=copy.deepcopy(rows[9,7]);changed=False
for g in bad['legacy_spectrum']:
 if not g['below_cutoff']:g['below_cutoff']=True;changed=True;break
negative=changed and not valid(bad)
assert known and negative and not failures
out={'table':'T864','checked_entries':4*len(rows),'total_entries':972,'failures':failures,'known_answer_control':bool(known),'negative_control_rejected':bool(negative),'controls':{'known':'Nonzero published figure-eight systole interval; valid filtered 9_7 record','negative':'Including the actual above-cutoff 9_7 candidate is rejected'},'checked_knots':len(rows),'method':l['method'],'tolerance':'1e-30','cutoff_separation':'1e-25','excluded_candidate_records':sum(len(r.get('excluded_above_cutoff',[])) for r in rows.values())}
print('LEGACY_RESULT_JSON '+json.dumps(out),flush=True)
