"""Check actual read-back entries against saved independent heat enclosures.
sage -python stored_check.py > stored-check.log
Requires stored-entries.json, heat-enclosures.json, companion-snapshots.json,
and document.json beside this script. Makes no website writes.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfi import RealIntervalField
from pathlib import Path
from independent_check import bounds, sane
from fractions import Fraction
import json

W=Path(__file__).resolve().parent; R=RealBallField(530); I=RealIntervalField(530)
rows=json.loads((W/'stored-entries.json').read_text())
K=('a','b','c','eps1','eps2','convention')
actual={tuple(str(r['params'][k]) for k in K):str(r['number']) for r in rows}
heats=json.loads((W/'heat-enclosures.json').read_text())
count=0; failures=[]
for shape in heats:
    for item in shape['checks']:
        key=tuple(item['key']); lo,hi=bounds(actual[key])
        hlo,hhi=map(QQ,item['enclosure'])
        ok=(hlo<=lo<=hhi) if lo==hi else (lo<=hlo<=hhi<=hi)
        if not ok: failures.append({'key':key,'reason':'stored interval misses independent spectral enclosure'})
        count+=1
assert len(actual)==count==642 and not failures

def ball(text):
    lo,hi=bounds(str(text)); return R(I(lo,hi))

def same(x,y):
    delta=x-y
    return bool(delta.is_finite() and delta.rad_as_ball()<R(10)**-90 and delta.contains_zero())

def at(f,s,c): return ball(actual[tuple(map(str,(*f,*s,c)))])
shapes={tuple(int(x) for x in key[:3]) for key in actual}
products=0; logsums=0; inverse=0; symmetries=0
for f in shapes:
    ds=[at(f,s,'det') for s in ((0,1),(1,0),(1,1))]
    ls=[at(f,s,'logdet') for s in ((0,1),(1,0),(1,1))]
    assert same(ds[0]*ds[1]*ds[2],R(4)); products+=1
    assert same(sum(ls),R(4).log()); logsums+=1
    for d,l in zip(ds,ls): assert same(d.log(),l); inverse+=1
    a,b,c=f
    if b==a: assert same(ds[1],ds[2]); symmetries+=1
    if a==c: assert same(ds[0],ds[1]); symmetries+=1

companions=json.loads((W/'companion-snapshots.json').read_text())
def value(tid,key,subkey=None):
    x=companions[tid]['Numbers'][str(key)]
    if subkey is not None: x=x[subkey]
    if isinstance(x,dict): x=x['number']
    return ball(str(x))

rect_theta=0; weber=0; singular=0
for a,b,c in shapes:
    if a!=1 or b!=0: continue
    r=c
    if str(r) in companions['T504']['Numbers']:
        eta=value('T506',r)
        for s,tid in [((0,1),'T507'),((1,0),'T505'),((1,1),'T504')]:
            assert same(at((a,b,c),s,'det'),(value(tid,r)/eta)**2); rect_theta+=1
    if str(r) in companions['T297']['Numbers']:
        assert same(at((a,b,c),(1,1),'det'),value('T297',r,'weber')**4)
        assert same(at((a,b,c),(1,1),'det'),2*value('T297',r,'ramanujan')**4); weber+=1
    if str(r) in companions['T295']['Numbers']:
        m=value('T295',r,'parameter'); D=(16/(m*(1-m)))**(QQ(1)/6)
        assert same(at((a,b,c),(1,1),'det'),D)
        assert same(at((a,b,c),(0,1),'det'),m.sqrt()*D)
        assert same(at((a,b,c),(1,0),'det'),(1-m).sqrt()*D); singular+=1

# The proposal's numerator 4 is wrong: the square m=1/2 gives D11=2.
assert not same((4/(R(QQ(1)/2)*(1-R(QQ(1)/2))))**(QQ(1)/6),R(2))
program=json.loads((W/'document.json').read_text())['Programs']['sage-example']['code']
ns={}; exec(program,ns)
assert same(ns['D'],at((2,1,3),(0,1),'det'))
print('STORED '+json.dumps({'checked_entries':count,'total_entries':642,'failures':failures,
  'independent_spectral_enclosures_reused':642,'determinant_products':products,
  'log_sums':logsums,'invertible_convention_checks':inverse,'boundary_symmetries':symmetries,
  'rectangular_theta_companion_checks':rect_theta,'weber_companion_shapes':weber,
  'singular_parameter_companion_shapes':singular,'proposal_numerator_four_rejected':True,
  'displayed_program_checked':True}),flush=True)
