"""Exact coefficient checks for the Cayley-box IDP examples."""

from math import comb


def lattice_count(d, alpha, beta, shift, dilation):
    """Count lattice points by multiplying the box-coordinate series."""
    answer = 0
    for b0 in range(dilation + 1):
        remaining = dilation - b0
        base = 1 + alpha * b0 + shift * dilation
        answer += sum(
            comb(d, j) * base ** (d - j) * (beta - base) ** j
            * comb(2 * d + remaining - j - 1, 2 * d - 1)
            for j in range(min(d, remaining) + 1)
        )
    return answer


def h_vector(d, alpha, beta, shift):
    ehrhart = [lattice_count(d, alpha, beta, shift, k) for k in range(2*d + 1)]
    return [
        sum((-1) ** (j-k) * comb(2*d + 1, j-k) * ehrhart[k] for k in range(j+1))
        for j in range(2*d + 1)
    ]


def tail_by_interior_counts(d, alpha, beta, shift):
    c = alpha + beta + (d + 1) * shift - 1
    top = c ** d
    first = (
        (c + alpha + shift) ** d
        + d * (c + beta + shift) * (c + shift) ** (d - 1)
    )
    second = (
        (c + 2 * alpha + 2 * shift) ** d
        + d * (c + alpha + beta + 2 * shift) * (c + alpha + 2 * shift) ** (d - 1)
        + d * (c + 2 * beta + 2 * shift) * (c + 2 * shift) ** (d - 1)
        + comb(d, 2) * (c + beta + 2 * shift) ** 2 * (c + 2 * shift) ** (d - 2)
    )
    return [second - (2*d + 1)*first + comb(2*d + 1, 2)*top,
            first - (2*d + 1)*top,
            top]


if __name__ == "__main__":
    for d, alpha, beta, shift in [(20, 50, 800, 0), (20, 5000, 80000, 1),
                                  (17, 100000, 1310000, 1), (17, 9289, 121783, 1)]:
        h = h_vector(d, alpha, beta, shift)
        values = h[d-2:d+1]
        assert values == tail_by_interior_counts(d, alpha, beta, shift)
        assert not any(h[d+1:])
        assert values[0] > values[1] < values[2]
        print((2*d, alpha, beta, shift), values)

