"""T734: Values of the Bettin–Conrey reciprocity function.

SageMath 10.9 and numberdb 0.1.10:
    sage -pip install numberdb
    sage -python generate.py             # verify all stored entries, no writes
    sage -python generate.py --publish   # add/update entries in this draft

The default selection consists of every reduced positive h/k with h,k <= 20,
ordered by max(h,k), h, k. The positive-real function is defined by
AM (arXiv:2402.14216v1), equation (1.1); c0 is a finite signed cotangent sum.
Exact rational arguments are enclosed before all Arb operations. Working
precision is numberdb.bits(digits, losing=128), 461 bits at 100 digits.
There is no truncation error. The measured enclosure and cancellation evidence
is in numerical-evidence.json; independent Estermann and contour checks are
in check_values.py and contour_check.py. No stored companion decimals are used.
"""
import argparse
import math
import os
import sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField


def selection(limit=20):
    for size in range(1, limit + 1):
        for h in range(1, size + 1):
            for k in range(1, size + 1):
                if max(h, k) == size and math.gcd(h, k) == 1:
                    yield {'x': str(QQ(h) / QQ(k))}


def cotangent_sum(h, k, field):
    pi = field.pi()
    return -sum((field(QQ(m) / QQ(k)) *
                 (pi * field(QQ((m * h) % k) / QQ(k))).cot()
                 for m in range(1, k)), field.zero())


def evaluate(params, digits=100):
    x = QQ(params['x'])
    if x <= 0:
        raise ValueError('x must be positive')
    h, k = int(x.numerator()), int(x.denominator())
    field = RealBallField(numberdb.bits(digits, losing=128))
    a = field(x) * cotangent_sum(h, k, field)
    b = cotangent_sum(k, h, field)
    c = -1 / (field.pi() * k)
    result = a + b + c
    if not result.is_finite() or result.accuracy() < 350:
        raise ArithmeticError('insufficient finite relative accuracy')
    return result


class BettinConreyValues(numberdb.Generator):
    table = 'T734'
    parameters = ('x',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, limit=20):
        yield from selection(limit)

    def value(self, params, digits):
        return evaluate(params, digits)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    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 = BettinConreyValues()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(g.publish())
    else:
        print(g.verify(sample=None))
