"""Reproduce NumberDB T855: Cardy's horizontal crossing probability.

Install numberdb in SageMath, then run:
    sage -pip install numberdb
    sage -python generate.py             # read-only verification of all entries
    sage -python generate.py --offline   # compute the default selection locally
    sage -python generate.py --publish   # fill this existing table, explicitly

For a private draft, configure your own NUMBERDB_API_KEY. Upload attribution
belongs in the calling environment. The publish method writes entries only;
it does not offer or publish a draft. It uses additive updates (removing=False).

r is the exact positive rational width/height ratio of a free-boundary rectangle
for the scaling limit of critical triangular-lattice site percolation (one open
color, p=1/2). The natural mathematical domain is real r>0; this generator's
reference enumeration uses rational identities. Default: the intrinsic square,
then s,1/s in increasing s>1, every reduced a/b with max(a,b)<=8 (43 entries).
The nonsquare selection is exploratory and its height bound is noncanonical.

Formula: with x=lambda(i*r),
 C(r)=Gamma(2/3)/(Gamma(4/3)*Gamma(1/3)) * x^(1/3)
       * 2F1(1/3,2/3;4/3;x).
See Kleban--Zagier (2003), §§2--3, equations (1), (3), (12), (13),
DOI 10.1023/A:1026012600583; Sheffield--Wilson (2011), §1 equation (2),
arXiv:1003.3271. Smirnov arXiv:0909.4499 identifies the triangular-lattice
scaling limit. All fractional powers are positive real powers.

Sage 10.9 with FLINT/Arb ball arithmetic computes lambda, gamma and 2F1. Use
numberdb.bits(digits, losing=128) bits (461 bits for 100 decimal digits).
For r<1 use color duality C(r)=1-C(1/r), propagating balls. For r=1 return
exact QQ(1)/2 by rotation and duality, never by snapping a decimal ball.
The computed lambda and hypergeometric value are real by their defining
series on this domain; extracting the real component retains the rigorous
enclosure, after checking finite components and imaginary zero containment.
No copied decimal argument or fixed-precision float is used. Output precision
is checked from the actual ball and by NumberDB's serializer. Offline evidence
records the measured radii and independent theta/integral comparisons.
"""
import argparse
from math import gcd

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

GUARD_BITS = 128


def checked_real(value):
    real, imag = value.real(), value.imag()
    if not real.is_finite() or not imag.is_finite() or not imag.contains_zero():
        raise ArithmeticError('Expected a finite enclosure of a real value')
    return real


def cardy_ball(r, digits=100):
    r = QQ(r)
    if r <= 0:
        raise ValueError('r must be positive')
    if r == 1:
        return QQ(1) / QQ(2)
    s = r if r > 1 else 1 / r
    precision = numberdb.bits(digits, losing=GUARD_BITS)
    real = RealBallField(precision)
    complex_ball = ComplexBallField(precision)
    x = checked_real(complex_ball(0, real(s)).modular_lambda())
    if not (x > 0 and x < 1):
        raise ArithmeticError('Cross-ratio not enclosed inside (0,1)')
    a = QQ(1) / QQ(3)
    b = QQ(2) / QQ(3)
    c = QQ(4) / QQ(3)
    h = checked_real(complex_ball(x).hypergeometric([a, b], [c]))
    factor = real(b).gamma() / (real(c).gamma() * real(a).gamma())
    result = factor * x**a * h
    if r < 1:
        result = 1 - result
    if not result.is_finite() or not (result > 0 and result < 1):
        raise ArithmeticError('Probability enclosure must be finite and in (0,1)')
    # Reject a non-informative result before any overlap comparison or upload.
    if not (real(result.rad().exact_rational()) < abs(result) * real(10)**(-digits - 15)):
        raise ArithmeticError('Ball does not support the requested digits plus guard')
    return result


class CardyHorizontal(numberdb.Generator):
    table = 'T855'
    parameters = ('r',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, height=8):
        if type(height) is not int or height < 1:
            raise ValueError('height must be a positive integer')
        yield {'r': '1'}
        ratios = sorted(QQ(a) / QQ(b) for a in range(2, height + 1)
                        for b in range(1, a) if gcd(a, b) == 1)
        for s in ratios:
            yield {'r': str(s)}
            yield {'r': str(1 / s)}

    def value(self, params, digits):
        return cardy_ball(params['r'], digits)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    flags = parser.add_mutually_exclusive_group()
    flags.add_argument('--publish', action='store_true')
    flags.add_argument('--offline', action='store_true')
    parser.add_argument('--height', type=int, default=8)
    options = parser.parse_args()
    generator = CardyHorizontal()
    if options.publish:
        print(generator.publish(height=options.height, removing=False))
    elif options.offline:
        from numberdb._write import to_text
        for params in generator.enumerate(height=options.height):
            print(params['r'], to_text(generator.value(params, generator.digits), generator.digits))
    else:
        print(generator.verify(sample=None))


if __name__ == '__main__':
    main()
