"""Certify the finite gain from retaining the time band of a double loss.

S removes one residue per wheel. J removes singleton classes independently.
The sensor reports whether any observed block lost exactly two sites.
"""
from collections import defaultdict
from fractions import Fraction
from math import isqrt, log, prod, sqrt
import json

from collisions14 import block_by_survival

GRID_BITS = 72
GRID = 1 << GRID_BITS


def windows(k):
    """Mark complete (2, 4) packets. Unmarked wheels still affect survival."""
    sieve = bytearray([1]) * (2 * k + 1)
    for p in range(2, isqrt(2 * k) + 1):
        if sieve[p]:
            sieve[p*p::p] = bytes(len(sieve[p*p::p]))
    schedule = []
    split = 3 * k // 2
    for band, (start, end) in enumerate(((k, split), (split, 2 * k))):
        primes = [p for p in range(start + 1, end + 1) if sieve[p]]
        for first in range(0, len(primes), 6):
            packet = primes[first:first + 6]
            if len(packet) == 6:
                schedule.extend([(packet[:2], band), (packet[2:], band)])
            else:
                schedule.append((packet, None))
    return schedule


def none_exclusive(singletons, twins, schedule, active):
    """Exact probability under S that no monitored block lost two sites."""
    denominator = 1
    paths = {(singletons, twins, 0): 1}
    for wheels, band in schedule:
        monitor = band in active
        for p in wheels:
            denominator *= p
            updated = defaultdict(int)
            for (s, t, losses), count in paths.items():
                empty = p - s - t
                if empty:
                    updated[s, t, losses] += count * empty
                if s:
                    after = min(3, losses + 1) if monitor else 0
                    updated[s - 1, t, after] += count * s
                if t:
                    after = min(3, losses + 2) if monitor else 0
                    updated[s, t - 1, after] += count * t
            paths = updated
        if monitor:
            remaining = defaultdict(int)
            for (s, t, losses), count in paths.items():
                if losses != 2:
                    remaining[s, t, 0] += count
            paths = remaining
    return Fraction(sum(paths.values()), denominator)


def none_independent(population, schedule, active):
    """Lower and upper probabilities for the same event under J without twins."""
    stages = []
    for wheels, band in schedule:
        monitor = band in active
        if stages and not monitor and not stages[-1][1]:
            stages[-1][0].extend(wheels)
        else:
            stages.append((list(wheels), monitor))
    if stages and not stages[-1][1]:
        stages.pop()  # No further observation depends on this final stage.

    mass = {population: GRID}
    for wheels, monitor in stages:
        denominator = prod(wheels)
        survives = prod(p - 1 for p in wheels)
        hit = denominator - survives
        updated = defaultdict(int)
        for alive, weight in mass.items():
            # Numerators of the binomial probabilities have a common denominator.
            numerator = survives ** alive
            scale = denominator ** alive
            for deaths in range(alive + 1):
                if not monitor or deaths != 2:
                    transition = (GRID * numerator) // scale
                    updated[alive - deaths] += weight * transition
                if deaths < alive:
                    numerator = numerator * (alive - deaths) * hit // ((deaths + 1) * survives)
        mass = {alive: value // GRID for alive, value in updated.items() if value >= GRID}
    lower = Fraction(sum(mass.values()), GRID)
    # Rounding a stochastic row and then the state vector each costs at most
    # (population + 1)/GRID per stage in total mass, including discarded zeros.
    error = Fraction(2 * (population + 1) * len(stages), GRID)
    return lower, min(Fraction(1), lower + error)


def check():
    """Six comparisons with a separate exact subset-survival calculation."""
    groups = [([5, 7], 0), ([11, 13, 17, 19], 1)]
    models = [((0, 1, 2, 5 * 7 * 11 * 13 * 17 * 19), 'S'), ((0, 1, 2, 3), 'J')]
    for active in ({0, 1}, {1}, {0}):
        for sites, model in models:
            states = {15: Fraction(1)}
            for wheels, band in groups:
                step = defaultdict(Fraction)
                for mask, weight in states.items():
                    transitions = block_by_survival(sites, wheels, (), model, mask)
                    for destination, probability in transitions.items():
                        losses = mask.bit_count() - destination.bit_count()
                        if band not in active or losses != 2:
                            step[destination] += weight * probability
                states = step
            exact = sum(states.values())
            if model == 'S':
                assert exact == none_exclusive(2, 1, groups, active)
            else:
                lower, upper = none_independent(4, groups, active)
                assert lower <= exact <= upper


def outward(value, up=False):
    """Print a rational bound to 12 decimal places with directed rounding."""
    scale = 10**12
    numerator = value.numerator * scale
    integer = -(-numerator // value.denominator) if up else numerator // value.denominator
    sign = '-' if integer < 0 else ''
    whole, fraction = divmod(abs(integer), scale)
    return f'{sign}{whole}.{fraction:012d}'


def interval(lower, upper):
    return [outward(lower), outward(upper, up=True)]


def binary_sensor(signed_none):
    # Differences S minus J for no double anywhere, early, or late.
    whole, early, late = (signed_none[label] for label in ('whole', 'early', 'late'))
    # Joint outcomes (early, late): 00, 10, 01, 11 by inclusion-exclusion.
    cells = [
        whole,
        (late[0] - whole[1], late[1] - whole[0]),
        (early[0] - whole[1], early[1] - whole[0]),
        (whole[0] - early[1] - late[1], whole[1] - early[0] - late[0]),
    ]
    lower = sum(max(0, left, -right) for left, right in cells) / 2
    upper = sum(max(abs(left), abs(right)) for left, right in cells) / 2
    global_upper = max(abs(bound) for bound in whole)
    signs = [int(left > 0) - int(right < 0) for left, right in cells]
    # The three "on" outcomes may be merged with zero loss if their signs agree.
    equal = signs[1:] in ([1, 1, 1], [-1, -1, -1])
    return dict(cell_signs=signs, whole_equals_split_certified=equal,
                two_band_tv=interval(lower, upper),
                gain_lower=outward(max(Fraction(0), lower - global_upper)))


def run():
    check()
    trials = []
    for k in (100, 250, 1000):
        population = round(2 * sqrt(k * log(k)))
        twins = round(log(k) / log(2))
        schedule = windows(k)
        events, signed_none = {}, {}
        for label, active in [('whole', {0, 1}), ('late', {1}), ('early', {0})]:
            no_s = none_exclusive(population - 2 * twins, twins, schedule, active)
            no_j_low, no_j_high = none_independent(population, schedule, active)
            signed_none[label] = (no_s - no_j_high, no_s - no_j_low)
            events[label] = dict(S=interval(1 - no_s, 1 - no_s),
                                 J=interval(1 - no_j_high, 1 - no_j_low),
                                 S_minus_J=interval(no_j_low - no_s, no_j_high - no_s))
        blocks = [sum(band == i for _, band in schedule) for i in (0, 1)]
        trials.append(dict(k=k, total_sites=population, twins_S=twins, twins_J=0,
                           complete_blocks=blocks, events=events, binary=binary_sensor(signed_none)))
    return dict(event='at least one observed block with exactly two site losses',
                grid_bits=GRID_BITS, checks=6, trials=trials)


if __name__ == '__main__':
    print(json.dumps(run(), indent=2))
