"""Check every stored interval and selected cross-route/precision controls.

Run: sage -python check_routes.py [numbers.json]
This imports the generator deliberately; independence comes from the prime
versus zero formulas, not from a second copy of the implementation. The
separate check_pi_values.py uses mpmath without importing this generator.
"""
from decimal import Decimal
from fractions import Fraction
import json
from pathlib import Path
import sys

from generate import HeatTrace, components


def exact_endpoint(endpoint):
    rational = endpoint.exact_rational()
    return Fraction(int(rational.numerator()), int(rational.denominator()))


def contains(text, value):
    decimal = Decimal(text)
    midpoint = Fraction(decimal)
    unit = Fraction(10) ** decimal.as_tuple().exponent
    return midpoint - unit <= exact_endpoint(value.lower()) <= exact_endpoint(value.upper()) <= midpoint + unit


folder = Path(__file__).parent
source = Path(sys.argv[1]) if len(sys.argv) > 1 else folder / 'numbers.json'
rows = json.loads(source.read_text())
selection = list(HeatTrace().enumerate())
assert [row['alpha'] for row in rows] == [parameters['alpha'] for parameters in selection]
precision_checks = []
prime_checks = []
for row in rows:
    key = row['alpha']
    stored = row['number']
    assert len(Decimal(stored).as_tuple().digits) == 100
    first = components(key)['value']
    assert contains(stored, first), key
    if 'pi' in key or key in ('1/12', '1/2', '1'):
        second = components(key, work_bits=640)['value']
        assert first.overlaps(second) and contains(stored, second), key
        precision_checks.append({'alpha': key, 'bits': [512, 640], 'both_enclosed': True})
    if key in ('pi/6', 'pi/3', 'pi/2'):
        prime = components(key, method='prime')
        assert first.overlaps(prime['value']) and contains(stored, prime['value']), key
        prime_checks.append({'alpha': key, 'prime_cutoff': prime['M'],
                             'prime_enclosure': str(prime['value']),
                             'zero_enclosure': str(first), 'both_enclosed': True})
report = {'checked_entries': len(rows), 'digits': 100,
          'exact_rational_endpoint_containment': True,
          'two_precision_checks': precision_checks, 'prime_cross_checks': prime_checks}
(folder / 'routes-results.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps({'checked_entries': len(rows), 'precision_checks': len(precision_checks),
                  'prime_cross_checks': len(prime_checks)}))
