"""Small exact replays for the pedal, six-part graph, and missing pulse (Python 3.11+).

The only inputs are the chord and pulse sets printed in the paper.
The separate score replay reads the 109-note transcription.
"""
from collections import Counter
from heapq import heappop, heappush
from itertools import combinations, product, permutations
from math import inf


def check(actual, expected, subject):
    if actual != expected:
        raise ValueError(f"{subject}: expected {expected}, obtained {actual}")


def sums(chord):
    counts = Counter((a + b) % 12 for a in chord for b in chord)
    return tuple(counts[i] for i in range(12))


def pedal():
    first, second = {0, 1, 3, 7}, {0, 3, 4, 10}
    presences = []
    for chord in (first, second):
        presences.append([{(x + t) % 12 for x in chord} for t in (0, 1, 4)])
    check(sums(first), (1, 2, 2, 2, 2, 0, 1, 2, 2, 0, 2, 0), "printed profile")
    for left, right in zip(*presences, strict=True):
        check(sums(left), sums(right), "corresponding chord profiles")
    intersections = [[a & b for a, b in combinations(seq, 2)] for seq in presences]
    check(intersections, [[{1}, {7}, {4}], [{4}, {4}, {4}]], "pair intersections")
    check([set.intersection(*seq) for seq in presences], [set(), {4}], "pedals")
    print("Pedal: no common class in X; class 4 (E) in Y.")


def adjacency(states):
    """Changes may be simultaneous. Each coordinate moves at most one level."""
    edges = {x: [] for x in states}
    for x, y in combinations(states, 2):
        steps = [abs(a - b) for a, b in zip(x, y, strict=True)]
        if max(steps) <= 1:
            cost = 3 * sum(steps)
            edges[x].append((y, cost))
            edges[y].append((x, cost))
    return edges


def minimum_costs(edges, source):
    distances = {source: 0}
    queue = [(0, source)]
    while queue:
        total, x = heappop(queue)
        if total != distances[x]:
            continue
        for y, increment in edges[x]:
            candidate = total + increment
            if candidate < distances.get(y, inf):
                distances[y] = candidate
                heappush(queue, (candidate, y))
    return distances


def voices():
    histograms = ((2, 2, 2, 0), (2, 0, 2, 2), (1, 3, 1, 1), (1, 1, 1, 3))
    layers = []
    for counts in histograms:
        notes = [level for level, n in enumerate(counts) for _ in range(n)]
        layers.append(set(permutations(notes)))
    check([len(layer) for layer in layers], [90, 90, 120, 120], "layer sizes")
    baseline = layers[0] | layers[1]
    expanded = set.union(*layers)
    x, y = (0, 0, 2, 2, 3, 3), (0, 2, 0, 3, 2, 3)
    costs = [minimum_costs(adjacency(states), x)[y] for states in (baseline, expanded)]
    check(costs, [36, 18], "free-part minima in semitones")
    pinned = {v for v in expanded if v[2:4] == (1, 1)}
    terminals = pinned & baseline
    graph = adjacency(pinned)
    check(len(terminals), 6, "number of pinned baseline states")
    check(any(adjacency(terminals).values()), False, "baseline isolation")
    check(set(len(graph[v]) for v in terminals), {4}, "C-neighbours per baseline state")
    reached = minimum_costs(graph, (0, 0, 1, 1, 2, 2))
    check(terminals <= reached.keys(), True, "pinned connectivity")
    check(reached[(2, 0, 1, 1, 0, 2)], 18, "pinned exchange in semitones")
    print("Six parts: 6 isolated endpoints connect; the free-part costs are 36 and 18.")


def rhythm():
    fixed = (0, 1, 3, 4, 10, 15, 21, 22)
    observed = {5, 6, 9, 11, 12, 18, 23}
    bank = {}
    for mask in product(range(2), repeat=8):
        one = sorted((a + 8 + 8 * mask[a % 8]) % 24 for a in fixed)
        two = sorted((a + 16 - 8 * mask[a % 8]) % 24 for a in fixed)
        cyclic = (fixed, one, two)
        if all(max(b - a for a, b in zip(s, [*s[1:], s[0] + 24])) <= 6 for s in cyclic):
            uid = sum(6**r * bit for r, bit in enumerate(mask))
            bank[uid] = (mask, cyclic)
    check(len(bank), 30, "valid assignments")
    candidates = {u for u, (_, parts) in bank.items() if observed <= set(parts[1])}
    check(candidates, {0, 1}, "two completions")
    check({u for u in candidates if sum(bank[u][0]) == 1}, {1}, "one move from UID 0")
    seams = [24 + min(right) - max(left) for left, right in zip(bank[1][1], bank[6][1])]
    check(seams, [2, 6, 6], "seam between UIDs 1 and 6")
    print("Rhythm: missing 8 or 16; after exactly one move from UID 0, missing 16.")


if __name__ == "__main__":
    pedal()
    voices()
    rhythm()
