"""Exact lower bound for the oscillation of strict-prefix variance."""
from fractions import Fraction as F
from itertools import product
from math import prod
import json

from dispersion import auto, orbit, subsets


def deviation(p, a):
    correlations = auto(p, a)[1:]
    average = F(sum(correlations), p-1)
    return max(abs(x-average) for x in correlations)


def coefficient(p, local):
    r = prod(local)
    multiplier = r//p
    for q, mask in local.items():
        if q == p:
            continue
        t = len(mask)
        c = F(t*(t-1), q-1)
        multiplier *= q if t == q else q*(t-c)-c
    return F(p*(p*p+5), 60*(p-1)*r*r)*multiplier


def inspect(local):
    values = orbit(local)
    spread = F(max(values.values())-min(values.values()), 12*prod(local)**2)
    if not all(local.values()):
        assert spread == 0
        return spread, []
    bounds = [(p, coefficient(p, local)*deviation(p, a)) for p,a in local.items()]
    assert all(0 <= bound <= spread for p,bound in bounds), local
    return spread, bounds


def census(p, q):
    best = worst = None
    flat = proper = 0
    for a,b in product(subsets(p), subsets(q)):
        if not (0<len(a)<p and 0<len(b)<q):
            continue
        proper += 1
        local = {p:a, q:b}
        spread, bounds = inspect(local)
        largest = max(v for _,v in bounds)
        if largest == 0:
            assert spread == 0
            flat += 1
            continue
        ratio = spread/largest
        entry = dict(masks=[sorted(a),sorted(b)], observed=str(spread),
                     bound=str(largest), ratio=str(ratio))
        if best is None or ratio < best[0]:
            best = ratio, entry
        if worst is None or ratio > worst[0]:
            worst = ratio, entry
    return dict(primes=[p,q], proper=proper, flat=flat, tightest=best[1], loosest=worst[1])


def experiment():
    extra = [{3:{0,1},5:{0,1},7:{0,1,3}}, {2:{0,1},5:{0,1},7:set(range(7))},
             {3:set(),5:{0,1}}]
    cases = []
    for local in extra:
        v, bounds = inspect(local)
        cases.append(dict(masks={p:sorted(a) for p,a in local.items()},observed=str(v),
                          bounds={p:str(x) for p,x in bounds}))
    return dict(pairs=[census(3,5),census(5,7)], extras=cases)


if __name__ == "__main__":
    print(json.dumps(experiment(), indent=2))
