"""Dimensionless squared angular velocity at axisymmetric bifurcations of Maclaurin spheroids -- numberdb.org/T629.

Run with SageMath (or passagemath) and numberdb installed:
    sage -pip install numberdb
    sage -python generate.py                 # verify all stored entries
    sage -python generate.py --fill-draft    # write entries; API key required

Filling sends values to the existing draft; it does not publish or offer it.
Default enumeration: k=1,...,10. The stored quantity is Omega^2/(4*pi*G*rho).
See argument-selection.md for coverage and certification.md for the proof.
Recovered from run 20261030T194506Z; see recovery-provenance.json.
The algorithms and prepared decimals were reproduced in the recovery run.

The exact QQ[x] root certificate is adapted from the public T627 and T628
attachments fetched on 2026-10-30. Roots are recomputed from (0,1), never
from stored eccentricities. At 100 digits, 500 working bits and 422 rational
bisections enclose the root. Its full uncertainty is propagated through
omega^2(x)=x*((1+3*x^2)*atan(1/x)-3*x)/2. A 700-bit repeat and independent
validated integral checks are in checks.py; see numerical-evidence.json.
"""
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.real_arb import RealBallField

WORKING_GUARD = 160
MIN_BITS = 500

@lru_cache(None)
def polynomials(k):
    k = int(k)
    if k < 1:
        raise ValueError('The branch index must be positive.')
    ring = PolynomialRing(QQ, 'x')
    x = ring.gen()
    p = [ring(1), x]
    r = [ring(0), ring(1)]
    ell = 2*k+2
    for n in range(1, ell):
        p.append(((2*n+1)*x*p[n] + n*p[n-1])/QQ(n+1))
        r.append(((2*n+1)*x*r[n] + n*r[n-1])/QQ(n+1))
    p, r = p[ell], r[ell]
    # d(q/p)/dx = -1/((1+x^2)p^2), q=p atan(1/x)-r.
    assert (1+x*x)*(r*p.derivative()-r.derivative()*p)-p*p == -1
    assert all(c >= 0 for c in p.list()) and p[0] > 0
    a, b = p*p+x*x, p*r+x
    numerator = (1+x*x)*(b*a.derivative()-b.derivative()*a)-a*a
    # H'=numerator/((1+x^2)A^2). Its numerator has one positive zero.
    assert numerator[0] < 0
    assert all(c >= 0 for c in numerator.list()[1:])
    assert numerator.leading_coefficient() > 0
    assert r.degree() < p.degree()
    assert b.degree() < a.degree()
    return p, r, a, b, numerator


def h(k, x):
    _, _, a, b, _ = polynomials(k)
    if x == 0:
        return x.parent().pi()/2
    return (1/x).arctan() - b(x)/a(x)


def root_enclosure(k, digits=100, working_bits=None):
    field = RealBallField(working_bits or max(MIN_BITS, numberdb.bits(digits, losing=WORKING_GUARD)))
    lo, hi = QQ(0), QQ(1)
    assert h(k, field(lo)) > 0 and h(k, field(hi)) < 0
    # H(0)>0; H decreases then increases to zero. The root is unique on x>0.
    steps = numberdb.bits(digits+22)
    for _ in range(steps):
        mid = (lo+hi)/2
        v = h(k, field(mid))
        if v > 0:
            lo = mid
        elif v < 0:
            hi = mid
        else:
            raise ArithmeticError('Increase working precision: unresolved sign.')
    xi = field((lo+hi)/2).add_error(field((hi-lo)/2))
    assert xi.is_finite() and xi > 0 and xi < 1
    return xi, lo, hi


def enclose(k, digits=100, working_bits=None):
    xi, lo, hi = root_enclosure(k, digits, working_bits)
    omega2 = xi*((1+3*xi*xi)*(1/xi).arctan()-3*xi)/2
    field = omega2.parent()
    assert omega2.is_finite() and omega2 > 0
    assert field(omega2.rad())/omega2 < field(10)**(-digits-18)
    return omega2, lo, hi


class MaclaurinSquaredAngularVelocity(numberdb.Generator):
    table = 'T629'
    parameters = ('k',)
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py', 'checks.py', 'argument-selection.md', 'certification.md',
             'numerical-evidence.json', 'skill-evidence.json', 'source-hashes.json',
             'companion_checks.py', 'companion-evidence.json', 'recovery-provenance.json')

    def enumerate(self, limit=10):
        for k in range(1, int(limit)+1):
            yield {'k': k}

    def value(self, params, digits):
        k = int(params['k'])
        value = enclose(k, digits)[0]
        if k == 1:
            return {'number': value, 'comment': 'The first axisymmetric branch continues to the Dyson rings. CITE{AKM}'}
        return value


def client_from_stdin():
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if '=' in key and key.split('=',1)[0].isupper():
            key = key.split('=',1)[1].strip().strip('\'"')
        return numberdb.Client(api_key=key)
    return None

if __name__ == '__main__':
    client = client_from_stdin()
    generator = MaclaurinSquaredAngularVelocity()
    if '--fill-draft' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(client=client, message='Certify the first ten axisymmetric Maclaurin squared angular velocities at 100 digits.'))
    else:
        report = generator.verify(sample=None, client=client)
        print(report)
        sys.exit(0 if report.ok else 1)
