"""T760: logarithmic Mahler measures of a+bx+cy.

Install numberdb in SageMath, then:
    sage -python generate.py             # preview, without writes
    sage -python generate.py --publish   # fill the assigned private draft
Configure the contributor's API key for reading/writing a private draft.
The generator never offers a draft or publishes it publicly.

The index 'sides' is a-b-c: positive, sorted, primitive integer triangle sides.
Default coverage: every isosceles such triple with c <= 12, together with every
primitive Pythagorean triple with c <= 100, in increasing (c,b,a) order.
The 84 identities include 1-1-1. These are practical finite bounds, not the
mathematical domain; the symmetry slice is exploratory reference coverage.

Cassaigne--Maillot, as stated by Lalin and Mittal, arXiv:1708.02466v1,
Introduction equation (1) and Section 2 equation (4), supplies the formula.
All integer/rational inputs are exact. Arb balls propagate their uncertainty
through the positive square root, principal dilogarithm, principal argument,
angles, logarithms and division by pi. Working precision is ceil(digits*log2(10))
plus 128 bits, measured over the entire default selection. The upper-half-plane
shape avoids the dilogarithm cut. No infinite series is truncated by this code.
The mathematical formula, branches and independence checks are documented in
research.md, checks.py, argument-selection.md and numerical-evidence.md.
"""
import os
import sys
from math import gcd, isqrt
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 selection(isosceles_height=12, right_height=100):
    """Complete bounded symmetry and arithmetic slices, without a coefficient cube."""
    triples = set()
    for c in range(1, isosceles_height + 1):
        for a in range(1, c + 1):
            for triple in ((a, a, c), (a, c, c)):
                x, y, z = triple
                if x + y > z and gcd(gcd(x, y), z) == 1:
                    triples.add(triple)
    # Euclid parametrization of every primitive right triangle in this bound.
    for m in range(2, isqrt(right_height) + 1):
        for n in range(1, m):
            c = m*m + n*n
            if c <= right_height and gcd(m, n) == 1 and (m-n) % 2:
                a, b = sorted((m*m - n*n, 2*m*n))
                triples.add((a, b, c))
    return sorted(triples, key=lambda t: (t[2], t[1], t[0]))


def triangle_measure(a, b, c, digits=100):
    """Enclose the measure for positive integer coefficients, in any order."""
    if any(type(v) is not int or v <= 0 for v in (a,b,c)):
        raise ValueError('positive native integer coefficients required')
    precision = numberdb.bits(digits, losing=GUARD_BITS)
    R, C = RealBallField(precision), ComplexBallField(precision)
    if 2*max(a,b,c) >= a+b+c:
        return R(max(a,b,c)).log()
    delta = 4*a*a*b*b - (a*a+b*b-c*c)**2
    assert type(delta) is int and delta > 0
    z = C(R(QQ(a*a+b*b-c*c)/(2*b*b)), R(delta).sqrt()/(2*b*b))
    alpha = R(QQ(b*b+c*c-a*a)/(2*b*c)).arccos()
    beta = R(QQ(a*a+c*c-b*b)/(2*a*c)).arccos()
    gamma = R(QQ(a*a+b*b-c*c)/(2*a*b)).arccos()
    D = z.polylog(2).imag() + (1-z).arg()*R(QQ(a)/b).log()
    result = (D + alpha*R(a).log() + beta*R(b).log() + gamma*R(c).log())/R.pi()
    if not result.is_finite() or not (R(result.rad()) < abs(result)*R(10)**(-digits-12)):
        raise ArithmeticError('finite precision enclosure requirement failed')
    return result


class LinearMahler(numberdb.Generator):
    table = 'T760'
    parameters = ('sides',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, isosceles_height=12, right_height=100):
        for a,b,c in selection(isosceles_height, right_height):
            yield {'sides': '%d-%d-%d' % (a,b,c)}

    def value(self, params, digits):
        a,b,c = map(int, str(params['sides']).split('-'))
        if not (1 <= a <= b <= c and a+b > c and gcd(gcd(a,b),c) == 1):
            raise ValueError('index is not a primitive sorted strict triangle')
        return {'number': triangle_measure(a,b,c,digits),
                'param-latex': '$(%d,%d,%d)$' % (a,b,c)}


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        token=sys.stdin.read().strip()
        if '=' in token and token.split('=',1)[0].isupper():
            token=token.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=token)
    generator=LinearMahler()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish())
    else:
        print(generator.preview())
