"""Direct carriers and the rank-one rigged-configuration bijection.

Strings use 1 for a ball, 0 for an empty box. Positions in printouts start at 1.
No third-party packages are required.
"""
from fractions import Fraction
from collections import Counter
from itertools import combinations, product


def sweep(word, capacity, load=0):
    """Return the new word, outgoing load and number of pickups on one pass."""
    result = []
    picks = 0
    for box in word:
        if box == "1" and load < capacity:
            load += 1
            picks += 1
            result.append("0")
        elif box == "0" and load:
            load -= 1
            result.append("1")
        else:
            result.append(box)
    return "".join(result), load, picks


def line(word, capacity):
    result, load, energy = sweep(word, capacity)
    if load:
        raise ValueError("Extend the empty right tail before using the finite word.")
    return result, energy


def ring(word, capacity):
    images = set()
    for load in range(capacity+1):
        result, out, _ = sweep(word, capacity, load)
        if out == load:
            images.add(result)
    assert len(images) == 1
    return images.pop()


def vacancy(length, size, rows):
    return length - 2*sum(min(size, j) for j, _ in rows)


def encode(word):
    """Highest paths have at least as many empties as balls in every prefix."""
    rows = []
    surplus = 0
    for n, box in enumerate(word):
        if box == "0":
            surplus += 1
            continue
        surplus -= 1
        if surplus < 0:
            raise ValueError("Path is not highest at this cut.")
        singular = [(j, r) for j, r in rows if r == vacancy(n, j, rows)]
        size = 0
        if singular:
            size, rigging = max(singular)
            rows.remove((size, rigging))
        shape = rows + [(size+1, 0)]
        rows.append((size+1, vacancy(n+1, size+1, shape)))
    return sorted(rows)


def decode(n, rows):
    rows = list(rows)
    reversed_word = []
    for length in range(n, 0, -1):
        singular = [(j, r) for j, r in rows if r == vacancy(length, j, rows)]
        if not singular:
            reversed_word.append("0")
            continue
        size, rigging = min(singular)
        rows.remove((size, rigging))
        if size > 1:
            shape = rows + [(size-1, 0)]
            rows.append((size-1, vacancy(length-1, size-1, shape)))
        reversed_word.append("1")
    assert not rows
    return "".join(reversed(reversed_word))


def shift_right(word, steps):
    k = steps % len(word)
    return word[-k:] + word[:-k] if k else word


def period(word, capacity):
    state = ring(word, capacity)
    n = 1
    while state != word:
        state = ring(state, capacity)
        n += 1
        assert n <= 2**len(word)
    return n


def carrier_checks():
    for bits in product("01", repeat=7):
        initial = "0"*7 + "".join(bits) + "0"*7
        for capacity in (1, 2, 3, 7):
            image, _ = line(initial, capacity)
            backward, _ = line(image[::-1], capacity)
            assert backward[::-1] == initial
            load = displacement = 0
            for box in initial:
                _, load, _ = sweep(box, capacity, load)
                displacement += load
            moment_change = sum(j*(int(new)-int(old))
                                for j, (old, new) in enumerate(zip(initial, image)))
            assert moment_change == displacement


def three_block_history(starts, steps):
    lengths = (3, 2, 1)
    size = max(starts) + 6*steps + 8
    word = "".join("1" if any(a <= j < a+b for a, b in zip(starts, lengths))
                   else "0" for j in range(size))
    history = [word]
    for _ in range(steps):
        word, _ = line(word, 6)
        history.append(word)
    return history


def count_angles():
    counts = Counter()
    for sites in combinations(range(10), 4):
        word = "".join("1" if j in sites else "0" for j in range(10))
        try:
            rows = encode(word)
        except ValueError:
            continue
        assert decode(10, rows) == word
        counts[tuple(sorted((j for j, _ in rows), reverse=True))] += 1
    assert counts == {(4,): 3, (3, 1): 21, (2, 2): 6, (2, 1, 1): 45, (1, 1, 1, 1): 15}
    print("Highest words at L=10, M=4 by partition:", dict(counts))


def reachable(initial, capacities):
    pending = [initial]
    seen = {initial}
    while pending:
        word = pending.pop()
        for capacity in capacities:
            image = ring(word, capacity)
            if image not in seen:
                seen.add(image)
                pending.append(image)
    return seen


def main():
    carrier_checks()
    count_angles()
    for starts in [(1, 9, 14), (1, 9, 26), (1, 16, 21)]:
        steps = 18
        final = three_block_history(starts, steps)[-1]
        occupied = [j for j, b in enumerate(final) if b == "1"]
        expected = []
        for start, size, shift in zip(starts, (3, 2, 1), (6, -2, -4)):
            edge = start + size*steps + shift
            expected.extend(range(edge, edge + size))
        assert occupied == sorted(expected)
    word = "000000111000010" + "0"*30
    rows = encode(word)
    assert decode(len(word), rows) == word
    for k in (1, 2, 3):
        image, _ = line(word, k)
        advanced = [(j, r+min(j,k)) for j,r in rows]
        assert encode(image) == advanced and decode(len(word), advanced) == image
        print("Capacity, riggings and occupied boxes:", k, advanced,
              [i for i,c in enumerate(image, 1) if c=="1"])
    print("Original rows:", rows)
    for time in range(6):
        occupied = [i for i,c in enumerate(word, 1) if c=="1"]
        energies = [line(word, k)[1] for k in (1,2,3,4)]
        assert energies == [2,3,4,4]
        print("Time, occupied boxes, energies:", time, occupied, energies)
        word, _ = line(word, 4)
    p = "111001000000"
    for d in range(len(p)):
        try:
            cut = encode(shift_right(p, -d))
        except ValueError:
            continue
        print("Ring cut, rows, lifted angles:", d, cut, [r+d for _,r in cut])
    assert period(p,4) == 24
    accessible = [len(reachable(p, ks)) for ks in [(4,), (1, 4), (1, 2)]]
    assert accessible == [24, 48, 96]
    print("Ring states reachable with {4}, {1,4}, {1,2}:", accessible)
    assert period("110000110000",4) == 3
    assert period("110001100000",4) == 6
    print("Ring periods: 24, 3, 6. F inverse times h:",
          Fraction(10-6,96), Fraction(-2+30,96))


if __name__ == "__main__":
    main()
