"""Exact algebra checks of the desktop report's ABSTRACT graph diagnostic.

No geometric realization is asserted. The universal growth/derived-set argument
is recorded separately in mathematical_checks.md; finite examples do not prove it.
"""
from fractions import Fraction as Q
from pathlib import Path
import hashlib
import json

ROOT = Path(__file__).resolve().parent

# A and B each have two loops; p:a->b and q:b->a complete a strongly
# connected graph. Their homology images are e1,e2,e3,0 respectively.
EDGES = {
    'a0': ('a', 'a', (1, 0, 0)), 'a1': ('a', 'a', (1, 0, 0)),
    'b0': ('b', 'b', (0, 1, 0)), 'b1': ('b', 'b', (0, 1, 0)),
    'p': ('a', 'b', (0, 0, 1)), 'q': ('b', 'a', (0, 0, 0)),
}
SIMPLE_CYCLES = [('a0',), ('a1',), ('b0',), ('b1',), ('p', 'q')]


def homology(cycle):
    return tuple(sum(EDGES[e][2][j] for e in cycle) for j in range(3))


def pairing(dual, cycle):
    return sum(a*b for a, b in zip(dual, homology(cycle)))


def recurrent_null_edges(dual):
    return {e for c in SIMPLE_CYCLES if pairing(dual, c) == 0 for e in c}


def full_perron(u, x, y, z):
    return (1 - 2*u**x)*(1 - 2*u**y) - u**z


def restricted_perron(u, x, y):
    return (1 - 2*u**x)*(1 - 2*u**y)


def main():
    # The three simple-cycle homology directions span the positive octant.
    assert set(map(homology, SIMPLE_CYCLES)) == {(1,0,0),(0,1,0),(0,0,1)}
    # Nonzero faces S=z-axis, T=x=0 plane; S is a proper face of T.
    s, eta = (0, 0, 1), (0, 1, 1)
    assert recurrent_null_edges(s) == {'a0','a1','b0','b1'}
    assert recurrent_null_edges(eta) == {'a0','a1'}
    # Polynomial identity det(I-A), using rational test values independently.
    for u in (Q(1,2), Q(1,3), Q(2,3)):
        for x in range(1,9):
            for y in range(1,9):
                for z in range(1,9):
                    matrix = [[1-2*u**x, -u**z], [-Q(1), 1-2*u**y]]
                    assert matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0] == full_perron(u,x,y,z)
    rows=[]
    for i in range(101):
        alpha=(1,2+i,1+i)
        assert all(pairing(alpha,c)>0 for c in SIMPLE_CYCLES)
        # For a two-loop bouquet with common length ell, log_2 growth=1/ell.
        exponent_a,exponent_b=Q(1,alpha[0]),Q(1,alpha[1])
        assert max(exponent_a,exponent_b)==1
        assert restricted_perron(Q(1,2),alpha[0],alpha[1])==0
        # At u=1/2 the other factor is strictly positive; A supplies the first root.
        assert 1-2*Q(1,2)**alpha[1] > 0
        rows.append({'i':i,'alpha':alpha,'log2_growth_DS':str(max(exponent_a,exponent_b)),
                     'log2_growth_DT':str(exponent_a),'P_DS_at_half':'0'})
    # All pairs: the maximum exponent is exactly the reciprocal minimum weight.
    for x in range(1,101):
        for y in range(1,101):
            assert max(Q(1,x),Q(1,y)) == Q(1,min(x,y))
    output={
        'status':'passed',
        'scope':'Exact arithmetic and combinatorial identities for an abstract directed graph, not a veering triangulation or a formal proof certificate.',
        'ambient_graph_strongly_connected':True,
        'cycle_cone_generators':sorted(set(map(homology,SIMPLE_CYCLES))),
        'positive_cohomology_cone':'x>0, y>0, z>0',
        'faces':{'S':'z axis','T':'x=0 face'},
        'P_full':'(1-2u^x)(1-2u^y)-u^z',
        'P_DS':'(1-2u^x)(1-2u^y)',
        'universal_argument_location':'mathematical_checks.md#abstract-graph-diagnostic',
        'checked_sequence_terms':len(rows),
        'sequence':rows,
        'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
    }
    (ROOT/'graph-diagnostic.json').write_text(json.dumps(output,indent=2)+'\n')
    print('PASS: abstract null-cycle graph, determinant, 101 constant-growth terms, and 10000 reciprocal-weight identities. No geometric realization claimed.')


if __name__=='__main__':main()
