"""Exact Euclidean bubble certificates and independent quadratures. Python 3, offline."""
import argparse
from collections import defaultdict
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import re


class Poly:
    """Integer polynomial with five formal variables. A sorted word encodes a monomial."""
    def __init__(self, terms):
        self.terms = {m: c for m, c in terms.items() if c}

    @staticmethod
    def of(value):
        return value if isinstance(value, Poly) else Poly({'': value})

    def __add__(self, other):
        terms = defaultdict(int, self.terms)
        for m, c in Poly.of(other).terms.items():
            terms[m] += c
        return Poly(terms)

    __radd__ = __add__

    def __neg__(self):
        return Poly({m: -c for m, c in self.terms.items()})

    def __sub__(self, other):
        return self + -Poly.of(other)

    def __rsub__(self, other):
        return Poly.of(other) + -self

    def __mul__(self, other):
        terms = defaultdict(int)
        for m, c in self.terms.items():
            for n, d in Poly.of(other).terms.items():
                terms[''.join(sorted(m+n))] += c*d
        return Poly(terms)

    __rmul__ = __mul__

    def derivative(self, variable):
        return Poly({m.replace(variable, '', 1): c*m.count(variable)
                     for m, c in self.terms.items() if variable in m})

    def substitute(self, **values):
        terms = defaultdict(int)
        for m, c in self.terms.items():
            remaining = ''.join(v for v in m if v not in values)
            terms[remaining] += c*math.prod(values[v] for v in m if v in values)
        return Poly(terms)

    def epsilon_coefficients(self, degree):
        if any(m.strip('e') or len(m) > degree for m in self.terms):
            raise ValueError('Expected a univariate polynomial in epsilon')
        return [self.terms.get('e'*k, 0) for k in range(degree+1)]


a, b, x, z, e = [Poly({v:1}) for v in 'abxze']


def deposited_root(text):
    """Parse only a sum of integer monomials in the three named invariants."""
    match = re.fullmatch(r'r1->Sqrt\[([a-z0-9*^+\-]+)\]', text)
    if not match:
        raise ValueError('Unexpected root definition')
    variables = {'m12': a, 'm22': b, 's13': -x}
    result = Poly.of(0)
    for term in match[1].replace('-', '+-').split('+'):
        if not term:
            raise ValueError('Empty term')
        value = Poly.of(-1 if term.startswith('-') else 1)
        for factor in term.lstrip('-').split('*'):
            if factor.isdecimal():
                value *= int(factor)
            else:
                token = re.fullmatch(r'(m12|m22|s13)(\^2)?', factor)
                if not token:
                    raise ValueError('Unexpected symbol in root')
                value *= variables[token[1]]
                if token[2]:
                    value *= variables[token[1]]
        result += value
    return result


def inspect_literals(src):
    match_integral = r'j\[PL1,([0-9,]+)\]'
    expression = src['master']
    if re.sub(match_integral, 'I', expression) != '(r1*(I+I))/eps':
        raise ValueError('Unexpected master prefactor or sum')
    powers = [[int(v) for v in m.split(',')] for m in re.findall(match_integral, expression)]
    if any(len(row) != 11 for row in powers):
        raise ValueError('PL1 requires eleven indices')
    active = [[(i,v) for i,v in enumerate(row,1) if v] for row in powers]
    if active != [[(2,1),(4,2),(8,2)], [(2,2),(4,1),(8,2)]]:
        raise ValueError('Unsupported propagator powers for this bridge')
    actual = {i:(p['momentum'],p['massSquared']) for i,p in src['propagators'].items()}
    if actual != {'2':('k2','m12'), '4':('k2+p1+p3','m22'), '8':('k1+k2-p2-p4','m12')}:
        raise ValueError('The selected tadpole and bubble propagators do not match')
    return {'masterIndex':src['masterIndex'], 'activePropagators':[2,4,8],
            'powersOnActivePropagators':[[v for _,v in row] for row in active],
            'spectatorPropagator':8, 'spectatorPower':2, 'sha256':src['sha256']}


def verify_file(path, src):
    data = path.read_bytes()
    if len(data) != src['bytes'] or hashlib.sha256(data).hexdigest() != src['sha256']:
        raise ValueError('Ancillary file size or digest mismatch')
    text = data.decode('ascii')
    compact = re.sub(r'\s+', '', text)
    lo, hi = src['lines']
    lines = ''.join(text.splitlines()[lo-1:hi])
    if re.sub(r'\s+', '', lines).removesuffix(',') != src['master'] or src['root'] not in compact:
        raise ValueError('Row or root differs from the pinned source')
    # Count list entries before the recorded expression. No Wolfram text is evaluated.
    before = compact.split('"Masters"->{', 1)[1].split(src['master'], 1)[0]
    depth, commas = 0, 0
    for char in before:
        if char in '([{':
            depth += 1
        elif char in ')]}':
            depth -= 1
        elif char == ',' and depth == 0:
            commas += 1
    if depth or commas+1 != src['masterIndex']:
        raise ValueError('Wrong one-based master index')
    props = compact.split('"Propagators"->{',1)[1].split('}|>',1)[0]
    momenta = re.findall(r'<\|"Type"->"Quadratic","Momentum"->([^,|]+)(?:,"Mass2"->([^|]+))?\|>', props)
    for i, item in src['propagators'].items():
        if momenta[int(i)-1] != (item['momentum'], item['massSquared']):
            raise ValueError('Source propagator differs from input')


def certificates(src, point):
    # All identities below are polynomial after multiplying by the stated common denominators.
    d, v = a-b, x+a+b
    D = v*v - 4*a*b
    Q = x*D
    K = D - x*v                      # f'/f = K/Q
    G = x*x - d*d                    # g = G/Q
    center = 2*x*z - x-d             # 2x(z-r)
    H = d*D + K*center               # h = H/(2xQ)
    p = b + d*z + x*z*(1-z)
    q = z*(1-z)
    cnum = -K-e*G                    # homogeneous coefficient c = cnum/Q
    checks = {
        'euclideanRoot': deposited_root(src['root'])-D,
        'fLogDerivative': 2*D-x*D.derivative('x')-2*K,
        'fixedMassDerivative': p.derivative('x')-q,
        'parameterIBP': 2*x*Q*q - 2*x*G*p - H*p.derivative('z'),
        'ibpSlope': H.derivative('z')-2*x*K,
        'jLowerA': H.substitute(z=1) - K*(x-d)-d*D,
        'jLowerB': -H.substitute(z=0) - K*(x+d)+d*D,
        'jDiagonal': K+cnum+e*G,
        'dottedEulerRelation': a*p.derivative('a')+b*p.derivative('b')+x*q-p,
        'depositedRowBoundary': 2*x*p - e*center*p.derivative('z') - 2*x*(1-2*e)*p - e*D,
        'depositedRowLowerA': (4*K+2*G)*(x-d) + 4*d*D - 2*D*(x+d),
        'depositedRowLowerB': (4*K+2*G)*(x+d) - 4*d*D - 2*D*(x-d)
    }
    for name, polynomial in checks.items():
        if polynomial.terms:
            raise ArithmeticError(f'{name} has nonzero exact coefficients: {polynomial.terms}')

    def scalar(poly):
        return poly.substitute(**point).epsilon_coefficients(0)[0]

    # Trial change determinant U=N/Q. Differentiate with masses and epsilon fixed BEFORE slicing.
    N = Q + e*D + cnum
    top_numerator = cnum*N + N.derivative('x')*Q - N*Q.derivative('x')
    denominator = Q*N
    n0, n1 = N.substitute(**point).epsilon_coefficients(1)
    if n1 == 0:
        raise ValueError('Trial determinant has no isolated regulator zero on this slice')
    pole = -Fraction(n0, n1)
    pn = top_numerator.substitute(**point).epsilon_coefficients(2)
    pd = denominator.substitute(**point).epsilon_coefficients(1)
    residue = sum(c*pole**k for k,c in enumerate(pn))/pd[1]
    if residue == 0:
        raise ArithmeticError('A canceled zero is not an actual pole')
    Q0 = scalar(Q)
    common = 2*point['x']*Q0
    result = {**point, 'delta':scalar(D), 'denominator':Q0,
              'bubbleDiagonalNumerator':cnum.substitute(**point).epsilon_coefficients(1),
              'bubbleLowerA':str(Fraction(scalar(H.substitute(z=1)),common)),
              'bubbleLowerB':str(Fraction(-scalar(H.substitute(z=0)),common)),
              'trialDetNumerator':[n0,n1], 'trialDetDenominator':Q0,
              'trialDiagonalNumerator':pn, 'trialDiagonalDenominator':pd,
              'rankLossEpsilon':str(pole), 'residue':str(residue)}
    return {name:len(poly.terms) for name,poly in checks.items()}, result


def simpson(rows, panels):
    return [math.fsum((1 if i in (0,panels) else 4 if i % 2 else 2)*v
                      for i,v in enumerate(column))/(3*panels) for column in zip(*rows)]


def numerical(point, panels):
    a, b, x, eps = (point[k] for k in ('a','b','x','epsilon'))
    if min(a,b,x,eps) <= 0 or panels <= 0 or panels % 2:
        raise ValueError('Use the positive Euclidean sheet, positive epsilon and even Simpson panel count')
    d, v = a-b, x+a+b
    D = v*v-4*a*b
    root = math.sqrt(D)
    f, r = x/root, (x+d)/(2*x)
    k, g = 1/x-v/D, (x*x-d*d)/(x*D)
    rp = -d/(2*x*x)
    ta, tb = a**(-eps), b**(-eps)
    C, Cp = (1-r)*ta+r*tb, rp*(tb-ta)

    def integrands(z):
        q = z*(1-z)
        p = b+d*z+x*q
        base = p**(-eps)             # all entries normalized by Gamma(epsilon)
        inv = base/p
        bp = -eps*q*inv
        return (base, bp, eps*z*inv, eps*(1-z)*inv,
                f*(base-C), f*(k*(base-C)+bp-Cp),
                root*inv, (v/root-root*(eps+1)*q/p)*inv)

    B, Bp, B21, B12, J, Jp, ME, MEp = simpson((integrands(i/panels) for i in range(panels+1)),panels)
    c = -k-eps*g
    lowerA = k*(1-r)-rp
    lowerB = k*r+rp
    Bm = c*B+lowerA*ta+lowerB*tb
    Jm = -eps*g*(J+f*C)
    MEm = -eps*g*ME+((x+d)*ta+(x-d)*tb)/(x*root)
    dotted_M = root*(B21+B12)/eps
    reduced_M = 2*f*(C-(1-2*eps)*B)/eps
    trial = B+(a*B21+b*B12)/x
    reduced_trial = (1+eps/x+c)*B+lowerA*ta+lowerB*tb
    return {'bubble':B, 'bubblePrime':Bp, 'bubblePrimeMatrix':Bm, 'b21':B21, 'b12':B12,
            'j':J, 'jPrimeDirect':Jp, 'jPrimeMatrix':Jm,
            'mE':ME, 'mEFromDots':dotted_M, 'mEFromBoundary':reduced_M,
            'mEPrimeDirect':MEp, 'mEPrimeMatrix':MEm, 'trial':trial, 'trialFromBasis':reduced_trial}


def sig(value):
    return float(format(value,'.12g'))


def bin_up(value):
    # Report differences rounded outwards to whole 1e-12 bins, including the minimum bin.
    return max(1,math.ceil(value*1e12))/1e12


def quadrature(point, panels, tolerance):
    if len(panels)<2 or any(p!=2*q for q,p in zip(panels,panels[1:])):
        raise ValueError('Expected successive doubled quadrature orders')
    values = [numerical(point,n) for n in panels]
    steps = [max(abs(left[key]-right[key]) for key in left) for left,right in zip(values,values[1:])]
    final = values[-1]
    pairs = [('bubblePrime','bubblePrimeMatrix'),('jPrimeDirect','jPrimeMatrix'),
             ('mE','mEFromDots'),('mE','mEFromBoundary'),('mEPrimeDirect','mEPrimeMatrix'),
             ('trial','trialFromBasis')]
    disagreement = max(abs(final[l]-final[r]) for l,r in pairs)
    if max(steps[-1],disagreement) >= tolerance:
        raise ArithmeticError(f'Quadrature convergence or identity failure: {steps}, {disagreement}')
    return {**point, **{key:sig(v) for key,v in final.items()},
            'maxRefinementByStep':[bin_up(s) for s in steps], 'maxIdentityDifference':bin_up(disagreement)}


def run(data):
    evidence = inspect_literals(data['ancillary'])
    exact, slice_result = certificates(data['ancillary'], data['slice'])
    num = [quadrature(point,data['simpsonPanels'],data['absoluteTolerance']) for point in data['points']]
    return {'source':data['source'], 'ancillary':evidence, 'exact':exact, 'slice':slice_result,
            'quadrature':num, 'simpsonPanels':data['simpsonPanels'],
            'conventions':'Polynomial coefficient arrays are in ascending powers of epsilon. Exact residuals count surviving monomials after clearing denominators. Quadrature values exclude Gamma(epsilon) and the common spectator. Maximum absolute changes are rounded upward to 1e-12 bins (minimum 1e-12).'}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--ancillary', type=Path, help='also verify the full pinned basis2l5p.m as inert ASCII')
    args = parser.parse_args()
    inputs = json.loads(Path(__file__).with_name('inputs.json').read_text(encoding='utf-8'))
    if args.ancillary:
        verify_file(args.ancillary, inputs['ancillary'])
    print(json.dumps(run(inputs),indent=2,allow_nan=False))
