"""Independent checks for T814; run with Sage and computed.json or stored.json.

sage -python checks.py [computed.json]
Entrywise method: independent weight enumeration, fundamental-weight coordinate
construction, complete homogeneous coefficient convolution and Jacobi-Trudi
Schur determinant times the positive Weyl denominator. No import from generate.
Every nonexact decimal component must contain this 700-bit certified result.
A component stored exactly is tested by narrow containment of that exact point;
its exactness additionally comes from the generator's algebraic square test.
All complete matrices satisfy symmetry, unitarity, S^2=C and (ST)^3=C numerically
with rigorous finite balls narrower than 2^-550. These finite checks are evidence,
not proofs of universal modular identities. Nonreal known and wrong-sign controls
prevent the checker from accepting a globally conjugated S.
"""
import json, math, os, sys, re
from pathlib import Path
from fractions import Fraction
from itertools import permutations
from collections import Counter

import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.real_mpfi import RealIntervalField

C = ComplexBallField(700)
R = RealBallField(700)
I = C(0, 1)
TOL = R(2) ** (-550)


def tuples(length, total):
    if length == 1:
        yield (total,)
    else:
        for a in range(total + 1):
            for rest in tuples(length - 1, total - a):
                yield (a,) + rest


def sectors(N, k):
    return [a for total in range(k + 1) for a in tuples(N - 1, total)]


def coords(N, a):
    # Fundamental weights in R^N; long roots e_i-e_j have norm squared two.
    return [QQ(N - 1 - 2*t)/2 + sum(QQ(a[j]) * (QQ(1 if t <= j else 0) - QQ(j+1)/N)
                 for j in range(N-1)) for t in range(N)]


def schur(a, z):
    N = len(z)
    partition = [sum(a[j:]) for j in range(N-1)] + [0]
    bound = partition[0] + N - 1
    h = [C(1)] + [C(0)] * bound
    for variable in z:
        for degree in range(1, bound + 1):
            h[degree] += variable * h[degree-1]
    determinant = C(0)
    for p in permutations(range(N)):
        sign = (-1) ** sum(p[t] > p[u] for t in range(N) for u in range(t+1,N))
        term = C(sign)
        for t in range(N):
            degree = partition[t] - t + p[t]
            term *= h[degree] if degree >= 0 else C(0)
        determinant += term
    return determinant


def independent(N, k, a, b):
    r = coords(N, b); L = N+k
    z = [(-2*I*R.pi()*(QQ(x)/L)).exp() for x in r]
    vacuum = R(1) / R(N * L**(N-1)).sqrt()
    for t in range(N):
        for u in range(t+1,N):
            vacuum *= 2*(R.pi()*(QQ(r[t]-r[u])/L)).sin()
    assert vacuum.is_finite() and vacuum > 0
    return vacuum * schur(a, z)


def component_bounds(text):
    text = text.strip()
    q = Fraction(text)
    if '.' not in text and 'e' not in text.lower():
        return q, q
    # A bare decimal denotes +/- one last-place unit, not an exact midpoint.
    mantissa, exponent = re.split('[eE]',text) if re.search('[eE]',text) else (text,'0')
    decimals = len(mantissa.partition('.')[2])
    power = int(exponent) - decimals
    ulp = Fraction(10)**power
    return q-ulp, q+ulp


def text_bounds(text):
    text=text.replace(' ','')
    if 'i*' not in text:
        return component_bounds(text), (Fraction(0),Fraction(0))
    if text.startswith('i*'):
        return (Fraction(0),Fraction(0)), component_bounds(text[2:])
    if text.startswith('-i*'):
        lo,hi=component_bounds(text[3:]); return (Fraction(0),Fraction(0)),(-hi,-lo)
    match=re.fullmatch(r'(.+)([+-])i\*(.+)',text)
    assert match,text
    real=component_bounds(match[1]); imag=component_bounds(match[3])
    if match[2]=='-': imag=(-imag[1],-imag[0])
    return real,imag


def check_stored(text, value):
    assert value.real().is_finite() and value.imag().is_finite()
    for (lo,hi), part in zip(text_bounds(text),(value.real(),value.imag())):
        assert part.is_finite() and R(part.rad()) < TOL
        low, high = QQ(lo.numerator)/lo.denominator, QQ(hi.numerator)/hi.denominator
        if lo == hi:
            assert low in part, (text,part,low)
        else:
            assert part.lower() >= low and part.upper() <= high, (text,part,low,high)
            assert high-low <= max(abs(low),abs(high))*QQ(1)/10**98, (text,high-low)
    return True


def near_zero(x, limit=TOL):
    assert x.real().is_finite() and x.imag().is_finite() and x.contains_zero() and R(abs(x).upper()) < limit, x


def mm(a,b):
    n=len(a)
    return [[sum((a[i][t]*b[t][j] for t in range(n)),C(0)) for j in range(n)] for i in range(n)]


def matrix_checks(N,k,weights,S,limit=TOL):
    size=len(weights)
    for i in range(size):
        for j in range(size): near_zero(S[i][j]-S[j][i],limit)
    dag=[[S[j][i].conjugate() for j in range(size)] for i in range(size)]
    unit=mm(S,dag); sq=mm(S,S)
    rho=[QQ(N-1-2*t)/2 for t in range(N)]
    c=QQ(k*(N*N-1))/(N+k)
    phases=[]
    for weight in weights:
        r=coords(N,weight)
        h=sum((r[t]-rho[t])*(r[t]+rho[t]) for t in range(N))/(2*(N+k))
        phases.append((2*I*R.pi()*(h-c/24)).exp())
    ST=[[S[i][j]*phases[j] for j in range(size)] for i in range(size)]
    cubed=mm(mm(ST,ST),ST)
    for i in range(size):
        for j in range(size):
            conjugate=int(weights[j]==tuple(reversed(weights[i])))
            near_zero(unit[i][j]-int(i==j),limit)
            near_zero(sq[i][j]-conjugate,limit)
            near_zero(cubed[i][j]-conjugate,limit)


def controls():
    x=independent(2,2,(1,),(1,)); check_stored('0',x)
    y=independent(2,2,(0,),(0,)); check_stored('1/2',y)
    z=independent(3,1,(1,0),(1,0))
    target=C(-R(1)/(2*R(3).sqrt()),QQ(1)/2)
    near_zero(z-target)
    rejected=0
    for text,value in [('1/3',y),('0',C(float('nan'))),('0',C(R(RealIntervalField(700)(-1000,1000)))),
                       ('-0.288675134594812882254574390250978728 - i*1/2',z)]:
        try: check_stored(text,value)
        except (AssertionError, ValueError): rejected+=1
        else: raise AssertionError('Deliberately wrong value was accepted')
    assert rejected==4
    return {'known_answer_control':True,'negative_control_rejected':True,
            'controls_detail':'SU(2)_2 exact vacuum 1/2 and interior 0; phase-sensitive SU(3)_1 fundamental diagonal. Rejected wrong rational, NaN, huge ball, conjugated phase.'}


def stored_ball(text):
    parts=[]
    for lo,hi in text_bounds(text):
        a,b=QQ(lo.numerator)/lo.denominator,QQ(hi.numerator)/hi.denominator
        parts.append(R(RealIntervalField(700)(a,b)))
    return C(*parts)


def companion_checks(N,k,weights,S,records):
    count=0
    dimensions={tuple(str(row['params'][p]) for p in ('N','k','weight')):row for row in records['T609']}
    globals_={tuple(str(row['params'][p]) for p in ('N','k','normalisation')):row for row in records['T610']}
    for i,a in enumerate(weights):
        row=dimensions[(str(N),str(k),','.join(map(str,a)))]
        check_stored(str(row['number']),S[i][0]/S[0][0]); count+=1
    for name,value in [('global',1/S[0][0]**2),('total',1/S[0][0])]:
        row=globals_[(str(N),str(k),name)]
        check_stored(str(row['number']),value); count+=1
    return count


def main():
    inp=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('computed.json')
    rows=json.loads(inp.read_text())
    if isinstance(rows,dict):
        rows=rows.get('Numbers',rows.get('Data'))
    result={'method':'700-bit Arb Jacobi-Trudi character times positive sine denominator; independent fundamental-weight coordinates and enumeration',
            'checked_entries':0,'total_entries':len(rows),'failures':[],**controls(),
            'blocks':[], 'su2_sine_checks':0,'level_one_fourier_checks':0,
            'working_bits':700,'residual_limit':'2^-550'}
    index=0
    companion_path=Path(__file__).with_name('companions.json')
    companions=json.loads(companion_path.read_text()) if companion_path.exists() else None
    result['companion_checks']=0
    for N in range(2,6):
        k=1
        while math.comb(k+N-1,N-1)<=10:
            weights=sectors(N,k); S=[]; stored_S=[]
            for a in weights:
                row=[]; stored_row=[]
                for b in weights:
                    expected={'N':str(N),'k':str(k),'weight1':','.join(map(str,a)),'weight2':','.join(map(str,b))}
                    record=rows[index]; assert {q:str(v) for q,v in record['params'].items()}==expected,(index,record,expected)
                    x=independent(N,k,a,b); check_stored(str(record['number']),x)
                    if N==2:
                        sine=(R(2)/R(k+2)).sqrt()*(R.pi()*QQ((a[0]+1)*(b[0]+1))/(k+2)).sin()
                        near_zero(x-sine); result['su2_sine_checks']+=1
                    if k==1:
                        aa=sum((j+1)*a[j] for j in range(N-1)); bb=sum((j+1)*b[j] for j in range(N-1))
                        fourier=(2*I*R.pi()*QQ(aa*bb)/N).exp()/R(N).sqrt()
                        near_zero(x-fourier); result['level_one_fourier_checks']+=1
                    row.append(x); stored_row.append(stored_ball(str(record['number']))); result['checked_entries']+=1; index+=1
                S.append(row); stored_S.append(stored_row)
            matrix_checks(N,k,weights,S)
            matrix_checks(N,k,weights,stored_S,limit=R(10)**(-94))
            if companions: result['companion_checks']+=companion_checks(N,k,weights,S,companions)
            result['blocks'].append({'N':N,'k':k,'dimension':len(weights),'entries':len(weights)**2,'matrix_identities':True})
            print('BLOCK_CHECKED',N,k,len(weights),flush=True)
            k+=1
    assert index==len(rows)==670
    result['limitations']='Finite-case identities and certified containment; exactness classification is established algebraically in generate.py, not inferred from these ball checks. No independent scientific verdict is issued by this builder.'
    print('CHECK_RESULTS',json.dumps(result),flush=True)

if __name__=='__main__': main()
