"""Check two five-loop reference blocks. Optional argument: pinned Esymb.txt."""
import hashlib
import itertools
import json
import re
import sys
from fractions import Fraction
from pathlib import Path

ALPHABET = 'abcdef'
SUFFIXES = ('bbcbdddd', 'dddddddd')
DIGEST = 'c5aaa42bf62c22ae29dcfae52b9a58164e2163f19751e8cc176cb0e761b57fef'
WORDS = [''.join(x) for x in itertools.product(ALPHABET, repeat=2)]
TERMS = re.compile(r'([+-]?)(?:(\d+(?:/\d+)?)\*)?SB\(([a-f](?:,[a-f])*)\)')


def assignment(text, name):
    start = re.search(r'^' + re.escape(name) + r'\s*:=\s*\[', text, re.M)
    if start is None:
        raise ValueError('Missing assignment: ' + name)
    end = re.search(r'\]\s*:', text[start.end():])
    if end is None:
        raise ValueError('Unterminated assignment: ' + name)
    literal = text[start.end():start.end() + end.start()]
    return ''.join(literal.replace('\\\n', '').split())


def parse_terms(literal, width):
    """Accept only signed rational multiples of SB(letter,...); never evaluate text."""
    result = {}
    offset = 0
    while offset < len(literal):
        match = TERMS.match(literal, offset)
        if match is None or (offset and not match[1]):
            raise ValueError('Unsupported coefficient syntax')
        word = match[3].replace(',', '')
        if len(word) != width or word in result:
            raise ValueError('Unexpected or repeated prefix')
        coefficient = Fraction(match[2] or '1')
        result[word] = -coefficient if match[1] == '-' else coefficient
        offset = match.end()
    return result


def extract(path):
    if path.stat().st_size != 8604108:
        raise ValueError('Unexpected ancillary size')
    raw = path.read_bytes()
    if hashlib.sha256(raw).hexdigest() != DIGEST:
        raise ValueError('Unexpected ancillary version')
    text = raw.decode('ascii').replace('\r\n', '\n')
    inputs = {'sourceSha256': DIGEST, 'blocks': {}}
    for width, labels, table in [(4, 'quadic8', 'Esymbquad[5]'),
                                 (8, 'octic93', 'Esymboct[5]')]:
        ordered = [label.replace(',', '') for label in
                   re.findall(r'E\(([a-f,]+)\)', assignment(text, labels))]
        blocks = re.split(r',(?=[+\-0-9S])', assignment(text, table))
        if len(ordered) != len(blocks):
            raise ValueError('Basis and coefficient table widths differ')
        for suffix in SUFFIXES:
            block_label = suffix[-width:]
            index = ordered.index(block_label)
            terms = parse_terms(blocks[index], 10 - width)
            compressed = {w: str(terms[w + suffix[:8 - width]]) for w in WORDS
                          if w + suffix[:8 - width] in terms}
            inputs['blocks'].setdefault(suffix, {})[labels] = compressed
    return inputs


def compare(inputs):
    rows = []
    for suffix in SUFFIXES:
        block = inputs['blocks'][suffix]
        for prefix in WORDS:
            # Missing monomials in these finite symbol polynomials have coefficient zero.
            q = Fraction(block['quadic8'].get(prefix, 0))
            o = Fraction(block['octic93'].get(prefix, 0))
            rows.append((prefix + suffix, q, o))
    disagreements = [word for word, q, o in rows if q != o]
    coefficients = {word: q for word, q, _ in rows}
    seed = 'bd' + 'dddddddd'
    reflected = seed.translate(str.maketrans('bcef', 'cbfe'))
    prediction, observed = coefficients[seed], coefficients[reflected]
    return {
        'source': 'arXiv:2204.11901v2', 'methodsPaper': 'arXiv:2609.32096v2',
        'sourceSha256': DIGEST, 'testedSuffixes': list(SUFFIXES),
        'testedWords': len(rows), 'bothNonzero': sum(bool(q and o) for _, q, o in rows),
        'bothZero': sum(q == o == 0 for _, q, o in rows),
        'disagreements': disagreements,
        'example': {'word': 'aa' + SUFFIXES[0],
                    'coefficient': str(coefficients['aa' + SUFFIXES[0]])},
        'reflection': {'knownWord': seed, 'heldOutWord': reflected,
                       'predicted': str(prediction), 'observed': str(observed)},
    }


def run(path=None):
    snapshot = json.loads(Path(__file__).with_name('inputs.json').read_text())
    if path and extract(path) != snapshot:
        raise ValueError('Pinned ancillary extraction differs from bundled inputs')
    result = compare(snapshot)
    # Change one octuple coefficient while retaining the independent quadruple table.
    snapshot['blocks'][SUFFIXES[0]]['octic93']['aa'] = '1/4'
    result['mutationMismatches'] = compare(snapshot)['disagreements']
    reflection = result['reflection']
    passed = (not result['disagreements'] and reflection['predicted'] == reflection['observed']
              and result['mutationMismatches'] == ['aa' + SUFFIXES[0]])
    result['status'] = 'passed' if passed else 'failed'
    return result


if __name__ == '__main__':
    if len(sys.argv) > 2:
        raise SystemExit('Usage: python3 -I check.py [Esymb.txt]')
    result = run(Path(sys.argv[1]) if len(sys.argv) == 2 else None)
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result['status'] == 'passed' else 1)
