"""Independent checks for T721. Run: sage -python independent_check.py entries.json results.json.

Default input is check-input.json beside this source. With no output argument,
prints RESULT_JSON for collection by a remote caller; with an output argument,
also writes that file. Does not import generate.py. Requires mpmath and numberdb/Sage.

1. Direct Gamma-ratio evaluation on a 512-point radius-1/4 Cauchy circle
   extracts all thirteen Taylor coefficients of G at 160 decimal digits.
2. Independently expands the published Mellin-Barnes boundary expression,
   JHEP09(2022)156 (5.21). Log-Gamma coefficients include even and odd zeta
   values; integer partitions (not the generator recurrence) exponentiate them.
   The coefficient of epsilon^0*(log s)^k is compared for all 90 entries;
   all pole coefficients are tested for cancellation.
3. The explicit one-loop Feynman integral and known low-loop values fix
   phase and normalization; altered sign/factorial controls must be rejected.

The numerical checks are high-precision independent agreement checks, not
new proofs of the Mellin-Barnes representation or certified contour quadrature.
Generator balls, separately checked, supply the stored rigorous enclosures.
"""
import sys,json,re,math,os,hashlib
from pathlib import Path
from decimal import Decimal
from fractions import Fraction
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
import mpmath as mp

mp.mp.dps=160
LIMIT=12

def qmp(q):
    return mp.mpf(q.numerator)/q.denominator

def component(text):
    text=text.strip()
    if text.startswith('['):
        a,b=text[1:-1].split(',');lo,hi=Fraction(a.strip()),Fraction(b.strip());return (lo+hi)/2,(hi-lo)/2
    if re.fullmatch(r'-?\d+',text):return Fraction(text),Fraction(0)
    d=Decimal(text.rstrip('?'));ulp=Fraction(10)**d.as_tuple().exponent
    return Fraction(d),ulp

def parts(text):
    pair=text.split(' + i * ')
    if len(pair)==1:pair.append('0')
    return [component(s) for s in pair]

def agrees(text,z,l,k):
    # Check every inexact component against its entire stored last-place interval.
    # Exact diagonal and zero components also have analytic low-degree controls.
    out=[]
    for idx,((c,r),v) in enumerate(zip(parts(text),[mp.re(z),mp.im(z)])):
        err=abs(v-qmp(c))
        if r:
            if not (mp.isfinite(v) and err < qmp(r)):return False
            out.append(err/qmp(r))
        else:
            d=l-k
            analytically_exact=(d==0 or (d==1 and idx==0) or (d==2 and idx==1))
            if not analytically_exact or not mp.isfinite(v) or err>mp.mpf('1e-125'):return False
    return True

def partitions(n,minimum=1):
    if n==0:
        yield ();return
    for j in range(minimum,n+1):
        for tail in partitions(n-j,j):yield (j,)+tail

PARTS={n:list(partitions(n)) for n in range(13)}
def exp_partition(b,n):
    result=mp.mpc(0)
    for part in PARTS[n]:
        term=mp.mpc(1)
        for j in set(part):
            m=part.count(j);term*=b[j]**m/math.factorial(m)
        result+=term
    return result

def cauchy_coefficients():
    N=512;rho=mp.mpf(1)/4
    roots=[mp.exp(2j*mp.pi*mp.mpf(j)/N) for j in range(N)]
    vals=[]
    for root in roots:
        z=rho*root
        vals.append(-mp.gamma(1-z)/mp.gamma(1+z)*mp.exp(-2*mp.euler*z-mp.j*mp.pi*z))
    return [mp.fsum(v*root**(-n) for root,v in zip(roots,vals))/N/rho**n for n in range(13)]

def mb_coefficients(l):
    # After removing epsilon^-l, the j-th summand has signed weight
    # (-1)^j*j*binomial(l+1,j), gamma ratio Q, and exp((j-1)*epsilon*L).
    rows=[]
    for j in range(1,l+2):
        b={1:(l+j-1)*mp.j*mp.pi}
        for n in range(2,l+1):
            mult=j+(l+1-j)*(-1)**n+(-1)**n*(j-1)**n-j**n-(-1)**n*l**n
            b[n]=mp.zeta(n)*mult/n
        e=[exp_partition(b,n) for n in range(l+1)]
        rows.append((j,(-1)**j*j*math.comb(l+1,j),e))
    coeff={k:mp.fsum(w*e[l-k]*(j-1)**k/math.factorial(k) for j,w,e in rows) for k in range(l+1)}
    pole_residuals=[abs(mp.fsum(w*e[n]*(j-1)**k/math.factorial(k) for j,w,e in rows)) for k in range(l) for n in range(l-k)]
    return coeff,max(pole_residuals or [mp.mpf(0)])

def main():
    inp=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('check-input.json')
    dest=Path(sys.argv[2]) if len(sys.argv)>2 else None
    doc=json.loads(inp.read_text());records=doc if isinstance(doc,list) else doc['Numbers']
    failures=[];comparisons=[];G=cauchy_coefficients();mb={};maxpole=mp.mpf(0)
    for l in range(1,13):
        mb[l],pole=mb_coefficients(l);maxpole=max(maxpole,pole)
    assert maxpole<mp.mpf('1e-125')
    max_ratio=mp.mpf(0)
    for r in records:
        l,k=(int(r['params'][n]) for n in ('l','k'))
        direct=(-1)**k*math.factorial(l+1)/mp.mpf(math.factorial(k))*G[l-k]
        m=mb[l][k];ok=agrees(r['number'],direct,l,k);mbok=agrees(r['number'],m,l,k)
        ratios=[]
        for (c,rad),v in zip(parts(r['number']),[mp.re(direct),mp.im(direct)]):
            if rad:ratios.append(abs(v-qmp(c))/qmp(rad))
        max_ratio=max([max_ratio]+ratios)
        if not ok or not mbok:failures.append({'params':r['params'],'cauchy':ok,'mellin_barnes':mbok})
        comparisons.append({'params':r['params'],'cauchy_in_stored_rectangle':ok,'mellin_barnes_in_stored_rectangle':mbok,'worst_last_place_error':str(max(ratios or [mp.mpf(0)]))})
    by={(int(r['params']['l']),int(r['params']['k'])):r['number'] for r in records}
    known=(agrees(by[1,0],2*mp.pi*mp.j,1,0) and agrees(by[1,1],mp.mpf(2),1,1)
           and agrees(by[2,0],3*mp.pi**2,2,0) and agrees(by[3,0],-16*mp.zeta(3)-4*mp.j*mp.pi**3,3,0))
    controls={'opposite_phase_rejected':not agrees(by[1,0],-2*mp.pi*mp.j,1,0),
              'extra_factorial_rejected':not agrees(by[3,2],2*mb[3][2],3,2),
              'nan_rejected':not agrees(by[2,0],mp.mpc(mp.nan),2,0),
              'wrong_diagonal_rejected':not agrees(by[12,12],mp.mpf(-12),12,12)}
    # Direct one-loop analytic integral continued from t<0: integral_0^1
    # da/(1-t*a*(1-a)). For t>4 on upper bank beta=sqrt(1-4/t)>0:
    # A1(t+i0)=2/(t*beta)*(log((1-beta)/(1+beta))+i*pi).
    # At s=10^-70, A1/s - (2 log(s)+2 i*pi) must vanish, at O(s log s).
    s=mp.mpf('1e-70');beta=mp.sqrt(1-4*s)
    integral_over_s=2/beta*(mp.log(4*s/(1+beta)**2)+mp.j*mp.pi)
    residual=abs(integral_over_s-(2*mp.log(s)+2*mp.j*mp.pi))
    known=bool(known and residual<mp.mpf('1e-65'))
    if not known:failures.append('known-answer controls failed')
    if not all(controls.values()):failures.append('negative control failed')
    result={'checked_entries':len(records),'total_entries':90,'failures':failures,'known_answer_control':known,'negative_control_rejected':all(controls.values()),'controls':controls,'gamma_cauchy':{'nodes':512,'radius':'1/4','working_decimal_digits':160,'coefficient_degrees':[0,12],'method':'direct complex Gamma values; discrete Cauchy extraction','limitations':'Numerical agreement test; no certified contour quadrature error claimed.'},'mellin_barnes':{'source':'JHEP09(2022)156 (5.21), published p.80','expansion':'integer-partition exponential of independent log-Gamma ratio, including even zeta values','maximum_pole_cancellation_residual':str(maxpole)},'one_loop_integral_asymptotic_residual':str(residual),'worst_stored_last_place_error':str(max_ratio),'comparisons':comparisons,'versions':{'mpmath':mp.__version__,'numberdb':numberdb.__version__,'python':sys.version},'input_sha256':hashlib.sha256(inp.read_bytes()).hexdigest(),'independence':'No generator imports. Direct Gamma contour extraction and independent Mellin-Barnes finite sum both check every row; both share the published convention. Not a separate critic verdict.','skill_manifest':'skill-manifest.json'}
    print('RESULT_JSON '+json.dumps(result))
    if dest is not None:dest.write_text(json.dumps(result,indent=2))
    return bool(failures)

if __name__=='__main__':raise SystemExit(main())
