"""Exact certificates for the third shell at every triangulation of a polygon.

Python 3.8+; standard library. Run this file directly.
"""
from collections import Counter, deque
from fractions import Fraction
from functools import lru_cache
from itertools import combinations
from math import comb


@lru_cache(None)
def triangulations(lo, hi):
    if hi - lo < 2:
        return (frozenset(),)
    return tuple(left | right | {(lo, split, hi)}
                 for split in range(lo + 1, hi)
                 for left in triangulations(lo, split)
                 for right in triangulations(split, hi))


def data(n):
    tris = triangulations(0, n - 1)
    diagonals = [frozenset(e for t in tr for e in combinations(t, 2)
                           if e[1] - e[0] > 1 and e != (0, n - 1))
                 for tr in tris]
    # Two triangulations differ by a flip iff they have a common codimension-one face.
    buckets = {}
    graph = [[] for _ in tris]
    for i, ds in enumerate(diagonals):
        for e in ds:
            face = ds - {e}
            if face in buckets:
                j = buckets.pop(face)
                graph[i].append(j)
                graph[j].append(i)
            else:
                buckets[face] = i
    assert not buckets and all(len(neighbors) == n - 3 for neighbors in graph)
    return tris, diagonals, graph


def distances(graph, root, radius=4):
    result = {root: 0}
    queue = deque([root])
    while queue:
        v = queue.popleft()
        if result[v] < radius:
            for w in graph[v]:
                if w not in result:
                    result[w] = 1 + result[v]
                    queue.append(w)
    return result


def local_table(n):
    tris, diag, graph = data(n)
    profile = Counter()
    for i, tr in enumerate(tris):
        root = diag[i]
        adj = [frozenset((u, v)) for u, v in combinations(root, 2)
               if any(set(u) | set(v) == set(t) for t in tr)]
        dist = distances(graph, i, radius=6)
        exact = Counter((root - diag[j], level) for j, level in dist.items())
        h = len(adj)
        if n == 7:
            e_sum = 0
            for triple in combinations(root, 3):
                triple = frozenset(triple)
                h3 = sum(pair <= triple for pair in adj)
                if h3 >= 2:
                    e_sum += exact[triple, 3] - 1 - h3
            m2 = sum(x.isdisjoint(y) for x, y in combinations(adj, 2))
            q = exact[root, 4]
            z = q - 1 - h - m2 - e_sum
            profile[h, q, m2, e_sum, z] += 1
        else:
            profile[h, exact[root, n-3], exact[root, n-2]] += 1
    return profile


def finite_roots(n):
    _, diag, graph = data(n)
    # The dihedral group permutes positions, preserves flips and shell sizes.
    index = {ds: i for i, ds in enumerate(diag)}
    unused = set(range(len(diag)))
    inequality_min = None
    orbits = 0
    while unused:
        i = next(iter(unused))
        for sign in (1, -1):
            for shift in range(n):
                img = frozenset(tuple(sorted(((shift + sign*a) % n, (shift + sign*b) % n)))
                                for a, b in diag[i])
                unused.discard(index[img])
        counts = Counter(distances(graph, i).values())
        gap = counts[3]**2 - counts[2]*counts[4]
        assert gap >= 0 and (not counts[3] or gap > 0)
        if inequality_min is None or gap < inequality_min:
            inequality_min = gap
        orbits += 1
    return len(diag), orbits, inequality_min


def bounded_parameters():
    count = 0
    worst = None
    for d in range(10, 100):
        for b in range((d-1)//2 + 1):
            a = d-1+b
            w_upper = d-2+3*b
            s2 = comb(d, 2)+a
            for e in range(-b, 2*w_upper-b+1):
                s3 = comb(d, 3)+(d-2)*a+e
                s4_upper = (comb(d, 4)+comb(d-2, 2)*a+comb(a, 2)
                            +(d-3)*e+10*w_upper-2*b)
                gap = s3**2-s2*s4_upper
                assert gap > 0
                if worst is None or gap < worst[0]:
                    worst = (gap, d, b, e)
                count += 1
    return count, worst


def large_parameters():
    # Lower s3/d^3, upper s2/d^2 and upper s4/d^4 for d >= 100.
    lo3 = Fraction(99*98, 6*100**2)
    hi2 = Fraction(1, 2) + Fraction(3, 200)
    hi4 = (Fraction(1, 24) + Fraction(3, 4*100) + Fraction(49, 8*100**2)
           + Fraction(25, 100**3))
    assert lo3**2 > hi2*hi4
    return lo3**2-hi2*hi4


if __name__ == '__main__':
    expected = {4: {(0, 1, 0): 2}, 5: {(1, 2, 0): 5},
                6: {(2, 5, 0): 6, (2, 4, 1): 6, (3, 3, 1): 2},
                7: {(3, 10, 1, 3, 2): 14, (4, 7, 1, 2, -1): 14,
                    (3, 14, 1, 4, 5): 7, (3, 8, 1, 2, 1): 7}}
    for n, table in expected.items():
        assert local_table(n) == table
    print('Quadrilateral through heptagon local tables verified.')
    for n in range(3, 13):
        print('n=%d, roots=%d, orbits=%d, minimum gap=%d' % ((n,) + finite_roots(n)))
    print('Parameter triples and worst (gap,d,b,e):', bounded_parameters())
    print('Large-dimensional scaled positive margin:', large_parameters())
