"""Generate T863, lengths of slopes on maximal cusps of hyperbolic knots.

Install dependencies into SageMath and run:
    sage -pip install snappy==3.3.2 numberdb
    sage -python generate.py                       # compute, do not write
    sage -python generate.py --publish             # fill this existing draft
Keep knotinfo-inputs.json beside this file. To resume the archived certified
intervals for validation, also keep geometry-checkpoints.json beside it and set
NUMBERDB_USE_CHECKPOINTS=1; omit that setting to recompute the geometry. Its archived public KnotInfo braids
fix the knot and peripheral marking, with corrected Rolfsen indices. No legacy
Manifold('n_k') names are used. PD notation supplies a separate identification
witness in the accompanying checks. Geometry is certified at >=540 bits by
SnapPy's verified maximal cusp translations, not by wrapping floating output.
A slope is p*meridian+q*preferred-longitude, primitive modulo simultaneous sign;
q>0 or (p,q)=(1,0). The default lists exactly the slopes of length <=6 on all
243 hyperbolic prime knots through ten crossings. All roots are positive.

The exact boundary longitude of 9_35 is 6 by Adams et al., Totally geodesic
Seifert surfaces II, Lemmas 5.1-5.2 and Theorem 5.3. KnotInfo identifies 9_35
as the (3,3,3) pretzel. For 4_1, L^2=p^2+12*q^2 from its regular ideal
triangulation: integer-square instances are returned as exact Sage integers.
Other values remain finite intervals; decimal zeros never trigger exactness.

No credentials, agent attribution or deployment paths are embedded here.
"""
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField
import snappy
import ast
import json
import math
import os
import hashlib
from pathlib import Path

ROOT=Path(__file__).resolve().parent
TORUS={(3,1),(5,1),(7,1),(8,19),(9,1),(10,124)}
INPUTS=json.loads((ROOT/'knotinfo-inputs.json').read_text())['knots']
KNOTS={(d['n'],d['k']):d for d in INPUTS if (d['n'],d['k']) not in TORUS}
assert len(KNOTS)==243

def exact_value(n,k,p,q):
    if (n,k,p,q)==(9,35,0,1):return ZZ(6)
    if (n,k)==(4,1):
        square=p*p+12*q*q; root=math.isqrt(square)
        if root*root==square:return ZZ(root)
    return None

def interval_endpoints(x):
    return [str(x.lower().exact_rational()),str(x.upper().exact_rational())]

def complex_endpoints(z):
    return [interval_endpoints(z.real()),interval_endpoints(z.imag())]

class Slopes(numberdb.Generator):
    table='T863'
    parameters=('n','k','p','q')
    type='R'
    digits=100
    rigour='proven'
    files=('generate.py','knotinfo-inputs.json','geometry-checkpoints.json')
    def __init__(self):
        self.geometry={};self.selections={}
        self.saved={}
        if os.environ.get('NUMBERDB_USE_CHECKPOINTS')=='1':
            packet=json.loads((ROOT/'geometry-checkpoints.json').read_text())
            assert packet['table']==self.table and packet['bits']==540
            assert packet['input_sha256']==hashlib.sha256((ROOT/'knotinfo-inputs.json').read_bytes()).hexdigest()
            self.saved={(r['n'],r['k']):r for r in packet['knots']}
    def packet(self,n,k,digits=100):
        prec=max(540,numberdb.bits(digits,losing=128))
        key=(n,k,prec)
        if key not in self.geometry:
            d=KNOTS[(n,k)]
            if (n,k) in self.saved and prec==540:
                r=self.saved[n,k]; R=RealIntervalField(540)
                from sage.rings.complex_interval_field import ComplexIntervalField
                C=ComplexIntervalField(540)
                def real(e):return R(QQ(e[0]),QQ(e[1]))
                mu=C(real(r['mu'][0]),real(r['mu'][1]));lam=real(r['lambda'])
                tau=(lam/mu).conjugate()
                self.geometry[key]=(mu,lam,tau,None)
                return self.geometry[key]
            word=ast.literal_eval(d['braid_notation'])
            if word and isinstance(word[0],list):word=word[0]  # KnotInfo 10_136 alternatives
            M=snappy.Link(braid_closure=word).exterior()
            for attempt in range(50):
                if M.solution_type()=='all tetrahedra positively oriented':break
                M.randomize()
            else:raise ArithmeticError(f'No geometric triangulation for {(n,k)}')
            mu,lam=M.cusp_translations(method='maximal',verified=True,bits_prec=prec)[0]
            tau=(lam/mu).conjugate()
            assert tau.imag()>0
            self.geometry[key]=(mu,lam,tau,M)
        return self.geometry[key]
    def selection(self,n,k):
        if (n,k) not in self.selections:
            mu,lam,tau,_=self.packet(n,k)
            a=abs(mu);x=tau.real();y=tau.imag();six=a.parent()(6)
            qmax=int((six/(a*y)).upper().floor());out=[];examined=[]
            for q in range(qmax+1):
                pmin=int((-q*x-six/a).lower().floor())
                pmax=int((-q*x+six/a).upper().ceil())
                for p in sorted(range(pmin,pmax+1),key=lambda p:(abs(p),p<0)):
                    if math.gcd(p,q)!=1 or (q==0 and p!=1):continue
                    vector=p*mu+q*lam; square=vector.real()**2+vector.imag()**2
                    exact=exact_value(n,k,p,q)
                    if exact is not None:
                        assert exact*exact in square
                        included=exact<=6
                    elif square.upper()<36:included=True
                    elif square.lower()>36:included=False
                    else:raise ArithmeticError(f'Unresolved slope boundary {(n,k,p,q)}')
                    examined.append({'p':p,'q':q,'square':interval_endpoints(square),'included':bool(included)})
                    if included:out.append((p,q))
            self.selections[(n,k)]=(out,{'qmax':qmax,'examined':examined})
        return self.selections[(n,k)][0]
    def enumerate(self):
        for n,k in sorted(KNOTS):
            for p,q in self.selection(n,k):yield {'n':n,'k':k,'p':p,'q':q}
    def value(self,params,digits):
        n,k,p,q=(int(params[v]) for v in self.parameters)
        if math.gcd(p,q)!=1 or not(q>0 or (p,q)==(1,0)):raise ValueError('Not a primitive representative')
        exact=exact_value(n,k,p,q)
        if exact is not None:return exact
        mu,lam,_,_=self.packet(n,k,digits)
        length=abs(p*mu+q*lam)
        assert length.lower()>0 and length.upper()<10**6
        assert length.absolute_diameter()<QQ(1)/10**(digits+10)
        return length

if __name__=='__main__':
    import sys
    g=Slopes()
    if '--publish' in sys.argv:
        outcome=g.publish(message='Fill checked slope lengths; proposal https://github.com/numberdb/numberdb-data/issues/408')
        print(outcome)
    elif '--compute' in sys.argv:
        for params in g.enumerate():
            print(','.join(str(params[k]) for k in g.parameters),to_text(g.value(params,g.digits),digits=g.digits),flush=True)

    else:
        print(g.verify(sample=None))
