"""Reproduce T862: both-directions wrapping on an untwisted rectangular torus.

Requires SageMath (tested 10.9) and `sage -pip install numberdb`.
  sage -python generate.py --offline  # compute default selection, no writes
  sage -python generate.py            # verify every stored value, read only
  sage -python generate.py --publish  # explicitly fill the authorized draft
Private reads need NUMBERDB_API_KEY, or NUMBERDB_KEY_FROM_STDIN=1 with a
key piped on stdin. Supply upload engine/model/run provenance in the environment.

The exact input r is height/width. R_b=1-X-P_(1,0)-P_(0,1), where X is
cross topology and P are primitive rank-one winding probabilities. The
complement consists of no occupied winding and the two axial-only sectors.
Both-directions wrapping includes diagonal winding and cross topology,
with one occupied color. Each configuration is counted once.
It defines an analytic CFT prediction, not a proved physical scaling limit.
Sources: Pruessner--Moloney (2003), (1)--(6); Ziff--Lorenz--Kleban
(1999), (9); Newman--Ziff (2001), III.1, (11)--(15). All roots are positive.

Explicit Gaussian tails and an eta omitted-product bound are propagated by
real ball arithmetic. For eta and the cross expression, use verified modular reciprocity when
r<1. Working precision is bits(digits)+180, with an explicit relative-radius
check. At 100 digits actual errors and cancellation are in metrics.json.
The parameter bound six is a noncanonical exploratory geometric reference
choice; the function domain is all positive real r.
"""
import argparse
from functools import lru_cache
import json, os, sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from numberdb._write import to_text


def selected_parameters():
    shapes=sorted({QQ(u)/v for u in range(1,7) for v in range(1,u+1)})
    for r in shapes:
        yield {'r':str(r)}


def theta(t,F,tolerance):
    """Enclose T(t)=sum exp(-pi*t*k^2), including an explicit tail."""
    t=QQ(t)
    if t<1:
        value,details=theta(1/t,F,tolerance)
        return value/F(t).sqrt(),dict(details,transformed=True)
    c=F.pi()*F(t); n=0
    while True:
        tail=2*(-c*(n+1)**2).exp()/(1-(-c*(2*n+3)).exp())
        if tail.upper()<tolerance.lower(): break
        n+=1
    value=F(1)+2*sum(((-c*k*k).exp() for k in range(1,n+1)),F(0))
    return value.add_error(tail),{'terms_each_side':n,'tail_bound':str(tail.upper()),'transformed':False}


def eta(r,F,tolerance):
    if r<1:
        value,details=eta(1/r,F,tolerance)
        return value/F(r).sqrt(),dict(details,reciprocal=True)
    q=(-2*F.pi()*F(r)).exp(); m=0
    while True:
        bound=q**(m+1)/(1-q)
        if bound.upper()<tolerance.lower(): break
        m+=1
    product=F(1)
    for k in range(1,m+1): product*=1-q**k
    # For 0<q<1, 1-sum(q^k) <= product(1-q^k) <= 1.
    assert bound.upper()<1
    return (-F.pi()*F(r)/12).exp()*product*F(1).add_error(bound),{
        'factors':m,'omitted_product_bound':str(bound.upper()),'reciprocal':False}


def cross(r,F,tolerance):
    s=max(r,1/r); values=[]; details=[]
    for t in [QQ(3)*s/8,QQ(8)*s/3,QQ(3)*s/2,QQ(2)*s/3]:
        v,d=theta(t,F,tolerance);values.append(v);details.append(dict(d,argument=str(t)))
    e,ed=eta(s,F,tolerance)
    left=values[0]*values[1];right=values[2]*values[3]
    return (left-right)/(2*e**2),{'theta':details,'eta':ed,'evaluated_r':str(s)}


def winding_probability(r,a,b,F,tolerance):
    A=QQ(a*a)/r+b*b*r
    c=2*F.pi()*F(A)/3; n=0
    while True:
        # Absolute coefficients 3+4+1=8, each exponential <= exp(-c*k^2).
        tail=8*(-c*(n+1)**2).exp()/(1-(-c*(2*n+3)).exp())
        if tail.upper()<tolerance.lower():break
        n+=1
    series=sum((3*(-9*c*k*k).exp()-4*(-4*c*k*k).exp()+(-c*k*k).exp()
                for k in range(1,n+1)),F(0)).add_error(tail)
    e,ed=eta(r,F,tolerance)
    return F(QQ(2)/(3*r)).sqrt()*series/e**2,{
        'positive_indices':n,'absolute_series_tail_bound':str(tail.upper()),'eta':ed}


@lru_cache(maxsize=256)
def compute(r_text,digits=100):
    r=QQ(r_text)
    if r<=0:raise ValueError('Require exact rational r>0 (height/width).')
    bits=numberdb.bits(digits,losing=180);F=RealBallField(bits)
    tolerance=F(2)**(-bits+32)
    x,xd=cross(r,F,tolerance)
    px,pxd=winding_probability(r,1,0,F,tolerance)
    py,pyd=winding_probability(r,0,1,F,tolerance)
    result=1-x-px-py
    relative=result.rad_as_ball()/abs(result)
    if not result.is_finite() or result.lower()<=0 or result.upper()>=1:
        raise ArithmeticError('Require a finite probability strictly inside (0,1).')
    if not relative.upper()<(F(10)**(-digits-15)).lower():
        raise ArithmeticError('Insufficient relative accuracy for requested digits.')
    return result,{'bits':bits,'accuracy_bits':int(result.accuracy()),
        'relative_radius_upper':str(relative.upper()),'cross':xd,'horizontal_only':pxd,'vertical_only':pyd,
        'subtraction_condition_bits_upper':str(((1+abs(x)+abs(px)+abs(py))/result).log(2).upper())}


class BothWrapping(numberdb.Generator):
    table='T862'
    parameters=('r',)
    type='R'
    digits=100
    rigour='proven'
    def enumerate(self):yield from selected_parameters()
    def value(self,params,digits):return compute(str(params['r']),digits)[0]


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--offline',action='store_true')
    parser.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    g=BothWrapping()
    if args.offline:
        print(json.dumps([{'params':p,'number':to_text(g.value(p,g.digits),g.digits)} for p in g.enumerate()],indent=2))
    elif args.publish:
        print(g.publish(removing=False))
        if os.environ.get('NUMBERDB_TABLE_RESULT_FILE'):
            from pathlib import Path
            Path(os.environ['NUMBERDB_TABLE_RESULT_FILE']).write_text(json.dumps({'tid':g.table})+'\n')
    else:
        result=g.verify(sample=None);print(result)
        if not result.ok:raise SystemExit(1)

if __name__=='__main__':main()
