"""Reproduce three calculations from the held-notes companion (Python 3.11+)."""

import json
from fractions import Fraction as Q
from itertools import combinations, product
from math import gcd, prod
from pathlib import Path

COMMA = Q(81, 80)
OCTAVE = Q(2)
PARTS = "SATB"
BASE = tuple(map(Q, ("1", "16/15", "9/8", "6/5", "5/4", "4/3",
                     "45/32", "3/2", "8/5", "5/3", "9/5", "15/8")))
TARGETS = {0: Q(1), 3: Q(6, 5), 4: Q(5, 4), 5: Q(4, 3), 7: Q(3, 2),
           8: Q(8, 5), 9: Q(5, 3)}


def require(condition, message):
    if not condition:
        raise ValueError(message)


def cents_ok(powered_ratio, cap, root=1):
    """Test |1200 log2(powered_ratio^(1/root))| <= cap with integer powers."""
    scale = gcd(1200, cap * root)
    folded = max(powered_ratio, 1 / powered_ratio)
    return folded ** (1200 // scale) <= OCTAVE ** ((cap * root) // scale)


def step24(ratio):
    numerator, denominator = ratio.numerator, ratio.denominator
    step = 0
    for prime, image in zip((2, 3, 5, 7), (24, 38, 56, 67), strict=True):
        while numerator % prime == 0:
            numerator //= prime
            step += image
        while denominator % prime == 0:
            denominator //= prime
            step -= image
    require(numerator == denominator == 1, f"Out of the 7-limit basis: {ratio}")
    return step


def transfer():
    """Enumerate the five-window constructed phrase, with partner P fixed."""
    e = Q(5, 4)
    fixed = {
        "A": (Q(9, 8), Q(3, 4), Q(3, 4), Q(3, 4), Q(4, 3)),
        "Q": (Q(7, 8), Q(7, 8), Q(243, 224), Q(5, 6), Q(5, 6)),
        "H": (Q(1, 2), Q(1, 2), Q(1, 2), Q(2, 3), Q(2, 3)),
    }
    expected_steps = {
        "A": (4, -10, -10, -10, 10), "B": (None, 8, 8, 8, None),
        "P": (-10, 0, 3, -6, -6), "Q": (-5, -5, 3, -6, -6),
        "H": (-24, -24, -24, -14, -14),
    }
    registers = {
        "A": (Q(2, 3), Q(3, 2)), "B": (Q(2, 3), Q(3, 2)),
        "P": (Q(2, 3), Q(9, 8)), "Q": (Q(4, 5), Q(9, 8)), "H": (Q(3, 8), Q(3, 4)),
    }
    targets = (Q(5, 4), Q(7, 6), Q(3, 2))
    tied = {"A": (1, 2), "B": (1, 2), "P": (3,), "Q": (0, 3), "H": (0, 1, 3)}
    cut_bits = {("B", 1): 1, ("B", 2): 2, ("P", 3): 8}
    default_p3 = Q(27, 32)
    palettes = [(e, e * COMMA)] * 3 + [(Q(15, 14), Q(243, 224)), (default_p3, Q(5, 6))]

    # The EDO trajectory already realizes its projected relations with all ties.
    require(tuple(map(step24, targets)) == (8, 5, 14), "Incorrect target map")
    for frame, ratio in enumerate(targets, 1):
        require(expected_steps["B"][frame] - expected_steps["P"][frame] == step24(ratio),
                "Incorrect projected dyad")
    for part, boundaries in tied.items():
        require(all(expected_steps[part][i] == expected_steps[part][i + 1] for i in boundaries),
                "Incorrect projected tie")

    results = {}
    for cap in (0, 20, 25):
        for deviation in (20, 35):
            used = []
            count = 0
            for b1, b2, b3, p2, p3 in product(*palettes):
                count += 1
                pitches = fixed | {
                    "B": (None, b1, b2, b3, None),
                    "P": (Q(3, 4), Q(1), p2, p3, default_p3),
                }
                band_passes = True
                for part, line in pitches.items():
                    lo, hi = registers[part]
                    for frame, ratio in enumerate(line):
                        if ratio is None:
                            continue
                        step = step24(ratio)
                        require(step == expected_steps[part][frame], "Incorrect note projection")
                        power = OCTAVE ** step
                        require(lo <= ratio <= hi and lo ** 24 <= power <= hi ** 24,
                                "Pitch outside a registered band")
                        band_passes &= cents_ok(ratio ** 24 / power, deviation, 24)
                if not band_passes or (b1, b2 / p2, b3 / p3) != targets:
                    continue

                mask = 4 if p3 != default_p3 else 0
                for part, boundaries in tied.items():
                    line = pitches[part]
                    for frame in boundaries:
                        before, after = line[frame:frame + 2]
                        if before == after:
                            continue
                        bit = cut_bits.get((part, frame), 0)
                        if not bit or not cents_ok(after / before, cap):
                            break
                        mask |= bit
                    else:
                        continue
                    break
                else:
                    used.append(mask)

            require(count == 32, f"Incorrect candidate count: {count}")
            feasible = [mask for mask in range(16) if any(mask & u == u for u in used)]
            results[cap, deviation] = [mask for mask in feasible
                                       if not any(other != mask and other & mask == other
                                                  for other in feasible)]
    require(results[25, 35] == [1, 2, 12] and results[25, 20] == [1],
            f"Wrong repair minima: {results}")
    require(all(not masks for (cap, _), masks in results.items() if cap < 25),
            "The 0- or 20-cent jump cap unexpectedly permits a repair")
    print("Constructed transfer: 32 JI candidates, masks 1, 2, 12 at 25/35 cents,")
    print("                     mask 1 at 25/20 cents, no repair at 0- or 20-cent jump caps")
    print("  Bits 1/2: early/late B reattack. Bit 4: alternate P note. Bit 8: P reattack.")


def nominal(midi):
    octave, pc = divmod(midi - 60, 12)
    return OCTAVE ** octave * BASE[pc]


def target(delta):
    if delta < 0:
        return 1 / target(-delta)
    octave, pc = divmod(delta, 12)
    return OCTAVE ** octave * TARGETS[pc]


def score():
    data = json.loads(Path(__file__).with_name("score.json").read_text(encoding="utf-8"))
    notes = data["notes"]
    ids = [note["id"] for note in notes]
    require(len(ids) == len(set(ids)) == 109, "Incorrect number of identified score notes")
    midi = [note["midi"] for note in notes]
    parts = [note["part"] for note in notes]
    starts = [Q(note["onset_q"]) for note in notes]
    ends = [Q(note["offset_q"]) for note in notes]
    pitches = dict(zip("CDEFGAB", (0, 2, 4, 5, 7, 9, 11)))
    for i, note in enumerate(notes):
        pitch = note["pitch"]
        semitone = pitches[pitch[0]] + pitch[1:-1].count("#") - pitch[1:-1].count("b")
        require(midi[i] == 12 * (int(pitch[-1]) + 1) + semitone,
                f"Pitch and MIDI disagree: {ids[i]}")
        require(parts[i] in PARTS and ids[i].startswith(parts[i] + "_")
                and 0 <= starts[i] < ends[i] <= 44, f"Invalid score occurrence: {ids[i]}")
    require(min(starts) == 0 and max(ends) == 44, "Incorrect score coverage")
    frames = []
    intervals = []
    previous = set()
    held = 0
    for q in sorted(set(starts + ends))[:-1]:
        active = tuple(i for i in range(109) if starts[i] <= q < ends[i])
        require(len(active) == len({parts[i] for i in active}), f"Overlapping voice at q={q}")
        held += len(previous.intersection(active))
        previous = set(active)
        pairs = []
        for low, high in combinations(sorted(active, key=lambda i: (midi[i], i)), 2):
            delta = midi[high] - midi[low]
            if delta % 12 not in TARGETS:
                continue
            base_residual = nominal(midi[high]) / (target(delta) * nominal(midi[low]))
            exponents = {1 / COMMA: -1, Q(1): 0, COMMA: 1}
            require(base_residual in exponents, f"Nonintegral comma target at q={q}")
            pairs.append((low, high, exponents[base_residual]))
        intervals.append(pairs)
        frames.append((q, active))
    require(len(frames) == 37 and held == 14, "Incorrect source windows or held notes")
    require(sum(map(len, intervals)) == 148, "Incorrect interval/window count")
    anchors = []
    for anchor in (("S", 72, 0), ("B", 48, 0), ("S", 60, 43)):
        matching = [i for i in range(109) if (parts[i], midi[i], starts[i]) == anchor]
        require(len(matching) == 1, f"Incorrect anchor: {anchor}")
        anchors.extend(matching)
    return midi, parts, starts, frames, intervals, set(anchors)


def all_pairs(midi, frames, intervals, anchors):
    """Certify the minimax optimum for the occurrence model and every n-grid."""
    quarter_offsets = {0: 0, 2: -2, 4: 0, 5: 1, 6: -2, 7: -1, 9: 1, 11: -1}
    witness = [quarter_offsets[pitch % 12] for pitch in midi]
    require(all(abs(k) <= 4 for k in witness), "Out of the comma envelope")
    require(all(witness[i] == 0 for i in anchors), "Nonzero anchor offset")

    # The 40-cent band contains each note's whole one-comma envelope.
    for pitch in set(midi):
        for z in (-1, 1):
            edo_ratio_power = OCTAVE ** (pitch - 60)
            require(cents_ok((nominal(pitch) * COMMA ** z) ** 12 / edo_ratio_power, 40, 12),
                    f"Envelope outside 40-cent band: MIDI {pitch}")
    residuals = [abs(4 * e + witness[high] - witness[low])
                 for pairs in intervals for low, high, e in pairs]
    require(max(residuals) == 1 and residuals.count(1) == 89, "Wrong quarter-comma witness")

    frame38 = next(i for i, (q, _) in enumerate(frames) if q == 38)
    cycle = (48, 55, 62, 65, 48)  # C3, G3, D4, F4, C3.
    require({midi[i] for i in frames[frame38][1]} == set(cycle), "Wrong q=38 notes")
    edges = {frozenset((midi[low], midi[high])) for low, high, _ in intervals[frame38]}
    require(all(frozenset(pair) in edges for pair in zip(cycle, cycle[1:])), "Missing q=38 edge")
    circulation = prod(target(high - low) for low, high in zip(cycle, cycle[1:]))
    require(circulation == COMMA, "Wrong q=38 circulation")

    # Actual ratios telescope. Thus the four residuals sum to -1 comma.
    # On the n-grid they sum to -n integer steps, requiring ceil(n/4) somewhere.
    # Flooring all n*z with the same origin preserves anchors and the envelope.
    # Each rounded difference lies between floor(n*(z_v-z_u)) and its ceiling.
    # Adding the integer target correction n*e commutes with either rounding,
    # so the verified 1/4 bound gives no more than ceil(n/4) grid steps.
    print("Locus iste, all consonant pairs: exact minimax 1/4 comma (89 of 148 tight)")
    print("  q=38 cycle target product 81/80. On the n-grid: ceil(n/4)/n commas.")


def bass_star(parts, starts, frames, intervals, anchors):
    """Carry minimum written-attack edits and their multiplicity across windows."""
    active_before = ()
    frontier = {(): (0, 1)}
    for (q, active), pairs in zip(frames, intervals, strict=True):
        positions = {i: index for index, i in enumerate(active)}
        bass_edges = [(positions[low], positions[high], e) for low, high, e in pairs
                      if "B" in (parts[low], parts[high])]
        held = [(old, positions[i]) for old, i in enumerate(active_before) if i in positions]
        new_attacks = [positions[i] for i in active if starts[i] == q]
        next_frontier = {}
        for state in product(*((0,) if i in anchors else (-1, 0, 1) for i in active)):
            if any(state[high] - state[low] + e != 0 for low, high, e in bass_edges):
                continue
            local_cost = sum(state[j] != 0 for j in new_attacks)
            best, ways = None, 0
            for predecessor, (cost, count) in frontier.items():
                if any(predecessor[old] != state[new] for old, new in held):
                    continue
                candidate = cost + local_cost
                if best is None or candidate < best:
                    best, ways = candidate, count
                elif candidate == best:
                    ways += count
            if ways:
                next_frontier[state] = (best, ways)
        require(next_frontier, f"No exact bass-star path through q={q}")
        active_before, frontier = active, next_frontier
    optimum = min(cost for cost, _ in frontier.values())
    multiplicity = sum(count for cost, count in frontier.values() if cost == optimum)
    require((optimum, multiplicity) == (6, 4), "Wrong bass-star attack optimum or multiplicity")
    print("Locus iste, exact bass-star: minimum 6 changed written attacks, 4 assignments")


def main():
    transfer()
    midi, parts, starts, frames, intervals, anchors = score()
    all_pairs(midi, frames, intervals, anchors)
    bass_star(parts, starts, frames, intervals, anchors)


if __name__ == "__main__":
    main()
