#!/usr/bin/env python3
"""Exhaustive exact-sign verification of Graffiti 292 for graph-atlas graphs n<=7."""
from fractions import Fraction
import math
import networkx as nx
import sympy as sp

from attack_graffiti_292 import graph_girth, gravity_mean_exact

x = sp.symbols('x')
checked = []
for atlas_index, graph in enumerate(nx.graph_atlas_g()):
    n = graph.number_of_nodes()
    if n == 0 or n > 7 or not nx.is_connected(graph) or graph_girth(graph) < 5:
        continue
    mean_gravity = gravity_mean_exact(graph)
    rhs = sp.oo if mean_gravity == 0 else sp.Rational(n * mean_gravity.denominator, mean_gravity.numerator)
    adjacency = sp.Matrix(nx.to_numpy_array(graph, dtype=int).tolist())
    characteristic = adjacency.charpoly(x).as_expr()
    roots = sp.polys.polytools.intervals(characteristic, eps=sp.Rational(1, 10**20))
    positive_upper_bounds = []
    for interval, multiplicity in roots:
        lower, upper = interval
        if lower > 0:
            positive_upper_bounds.extend([upper] * multiplicity)
    if positive_upper_bounds:
        least_positive_upper = min(positive_upper_bounds)
        if not least_positive_upper <= rhs:
            raise AssertionError((atlas_index, n, characteristic, least_positive_upper, rhs))
    checked.append((atlas_index, n, graph.number_of_edges(), characteristic, rhs))

print(f'exact_checked={len(checked)}')
for row in checked:
    print(row)
print('OK: every graph-atlas case n<=7 passes with exact rational root isolation.')
