"""Independent full-range density check: sage -python check_densities.py.

Input is entries.json, or main(path). No generator code is imported.
Klein polar planes and face normals supply h and geometric checks. A
regularized Schlaefli integral supplies whole-cell volume, with independent
Hurwitz-zeta ideal anchors. Integrating cosh(t)^2 supplies the hyperball
volume over a Gauss-Bonnet base polygon. mpmath quadrature is heuristic;
rigorous generation bounds are separately obtained with Arb.
All reusable source dependencies accompany this file.
"""
import json
import sys
from pathlib import Path
from fractions import Fraction
import mpmath as mp
from geometry import geometry, symbolic_identities, R, rat, matches_decimal
from volume_integral import independent_volume

SHAPES = {'tetrahedron': (4, 3, 24, 7), 'cube': (8, 3, 48, 7),
          'octahedron': (6, 4, 48, 5)}
SOURCE = {'tetrahedron': {7: '0.82251', 8: '0.76673', 9: '0.71663', 20: '0.41431'},
          'cube': {7: '0.68839367', 8: '0.64892530', 9: '0.60963750', 20: '0.35583872'},
          'octahedron': {5: '0.76892924', 6: '0.69414405', 7: '0.63156984', 20: '0.28967074'}}


def decimal(text):
    from fractions import Fraction
    from decimal import Decimal
    f = Fraction(text)
    u = Fraction(Decimal(1).scaleb(Decimal(text).as_tuple().exponent))
    return mp.mpf(f.numerator)/f.denominator, mp.mpf(u.numerator)/u.denominator


def acceptable(text, expected):
    try:
        centre, ulp = decimal(text)
        return bool(mp.isfinite(expected) and mp.isfinite(centre)
                    and 0 < ulp < abs(centre)*mp.mpf('1e-95')
                    and abs(expected-centre) < ulp)
    except (ValueError, ArithmeticError):
        return False


def independent_density(cell, p, height, dps):
    with mp.workdps(dps):
        N, sides, M, _ = SHAPES[cell]
        h = mp.mpf(str(height.mid()))
        a = mp.pi/p
        area = (sides-2)*mp.pi-sides*2*a
        assert area > 0
        normal_integral = mp.quad(lambda t: mp.cosh(t)**2, [0, h/2, h])
        V = independent_volume(cell, p, dps)
        return +(N*area*normal_integral/V), V, area, normal_integral


def main(path=None):
    mp.mp.dps = 145
    path = Path(path or Path(__file__).with_name('entries.json'))
    entries = json.loads(path.read_text())
    keys = [(str(e['params']['cell']), int(e['params']['p'])) for e in entries]
    assert keys == [(cell, p) for cell, (_, _, _, start) in SHAPES.items()
                    for p in range(start, 31)]
    result = {'input_file': path.name, 'checked_entries': 0, 'total_entries': 74,
              'failures': [], 'known_answer_control': False,
              'negative_control_rejected': False, 'records': [], 'source_controls': [],
              'limitations': 'Schlaefli and normal-coordinate quadratures are heuristic independent checks; Arb generation supplies rigorous enclosures.',
              'skill_manifest': 'skill-manifest.json',
              'skill_bundle_sha256': '1141919a3e18f5ffbac8ac7bc2b6977a16f65189239ff3d9dbee3a8ed002c026'}
    assert symbolic_identities()
    assert abs(mp.quad(lambda t: 1+t*t, [0, 1])-mp.mpf(4)/3) < mp.mpf('1e-140')
    cat = (mp.zeta(2, mp.mpf(1)/4)-mp.zeta(2, mp.mpf(3)/4))/16
    assert abs(cat-mp.catalan) < mp.mpf('1e-140')
    cl = mp.sqrt(3)/72*sum(s*mp.zeta(2, mp.mpf(k)/6)
                            for k, s in [(1, 1), (2, 1), (4, -1), (5, -1)])
    assert str(cl).startswith('1.014941606409653625021202554274520285941689')
    h6 = mp.log((1+mp.sqrt(5))/2)
    assert abs(mp.quad(lambda t: mp.cosh(t)**2, [0, h6])
               -(mp.sqrt(5)/2+2*h6)/4) < mp.mpf('1e-140')
    assert abs(mp.quad(lambda t: mp.cosh(t)**2, [0, 0])) == 0
    computed = {}
    for e, (cell, p) in zip(entries, keys):
        h, geom = geometry(cell, p)
        if cell == 'octahedron' and p == 6:
            assert (h-((1+R(5).sqrt())/2).log()).contains_zero()
        d1, _, _, _ = independent_density(cell, p, h, 115)
        d2, V, area, normal = independent_density(cell, p, h, 135)
        assert abs(d1-d2) < mp.mpf('1e-110')
        assert 0 < d2 < 1
        N, q, M, _ = SHAPES[cell]
        assert M == 2*q*N
        # Verify the whole-cell and chamber coefficients independently.
        a = mp.pi/p
        assert Fraction(N*(q-2), M) == Fraction(1, 2)-Fraction(1, q)
        hm = mp.mpf(str(h.mid()))
        chamber_form = (mp.pi/2-a-mp.pi/q)*(mp.sinh(2*hm)+2*hm)/(4*V/M)
        assert abs(d2-chamber_form) < mp.mpf('1e-130')
        centre, ulp = decimal(e['number'])
        ok = acceptable(e['number'], d2)
        if not ok:
            result['failures'].append(f'{cell},{p}: stored decimal failed independent comparison')
        result['records'].append({'params': e['params'], 'stored': e['number'],
                                  'density': mp.nstr(d2, 133), 'volume': mp.nstr(V, 133),
                                  'base_area': mp.nstr(area, 133), 'normal_integral': mp.nstr(normal, 133),
                                  'error_last_places': mp.nstr(abs(centre-d2)/ulp, 20),
                                  'quadrature_precision_difference': mp.nstr(abs(d1-d2), 10),
                                  'geometry': geom})
        computed[cell, p] = (d2, h, V, area)
        if p in SOURCE[cell]:
            source = SOURCE[cell][p]
            m, u = decimal(source)
            agrees = bool(abs(m-d2) < u*mp.mpf('0.51')+mp.mpf('1e-9'))
            assert agrees, (cell, p, source, d2)
            result['source_controls'].append({'cell': cell, 'p': p, 'density': source, 'passes': agrees})
        result['checked_entries'] += 1
        print('CHECKPOINT', cell, p, mp.nstr(d2, 22), flush=True)
    result['known_answer_control'] = True
    first = entries[0]['number']
    d, h, V, area = computed['tetrahedron', 7]
    hm = mp.mpf(str(h.mid()))
    wrong_double_height = 4*area*(mp.sinh(4*hm)+4*hm)/(4*V)
    negatives = {
        'doubled_height': not acceptable(first, wrong_double_height),
        'density_inverted': not acceptable(first, 1/d),
        'omitted_chamber_factor': not acceptable(first, 24*d),
        'missing_halfhyperball_factor': not acceptable(first, 2*d),
        'wrong_full_angle': not acceptable(first, independent_density('tetrahedron', 7, geometry('tetrahedron', 7, 1)[0], 115)[0]),
        'swapped_cube_octahedron': not acceptable(next(e['number'] for e,k in zip(entries, keys) if k==('cube',7)), computed['octahedron',7][0]),
        'perturbed_result': not acceptable(first, d+mp.mpf('1e-75')),
        'nan': not acceptable(first, mp.nan),
        'vacuous_stored_interval': not acceptable('0.8', d),
        'vacuous_geometry_ball': not matches_decimal(first, R(1).add_error(1))}
    assert all(negatives.values()), negatives
    result['negative_controls'] = negatives
    result['negative_control_rejected'] = True
    result['all_plane_pairs'] = sum(x['geometry']['pairs'] for x in result['records'])
    result['all_edge_contacts'] = sum(x['geometry']['edge_contacts'] for x in result['records'])
    result['all_facet_clearances'] = sum(x['geometry']['nonincident_facet_checks'] for x in result['records'])
    result['maximum_error_last_places'] = max((x['error_last_places'] for x in result['records']), key=mp.mpf)
    print('RESULTS_JSON='+json.dumps(result), flush=True)
    try:
        path.with_name('check-results.json').write_text(json.dumps(result, indent=2))
    except OSError:
        pass
    assert not result['failures']
    return result


if __name__ == '__main__':
    main(sys.argv[1] if len(sys.argv)>1 else None)
