"""Standard-library check of the counterexample to the Odd Sum conjecture (Ahmed-Snevily) at n = 17.

1. t(pi) is computed two ways: directly from the definition (sum of run counts over all
   subsequences of length >= 3) and by the O(n^3) turning-point formula. They must agree.
2. The permutation below has t = 798783, the proved value of tmax(17).
3. It violates the Odd Sum conjecture: pi_4 + pi_14 is even.
Optimality of 798783 is established separately by optimum_cpsat.py / optimum_highs.py.
"""
import itertools, random
from t_definition import t as t_def
from t_formula import t as t_fast

PI = [8, 14, 3, 15, 6, 10, 2, 17, 7, 12, 1, 16, 5, 11, 4, 13, 9]
TMAX17 = 798783

for n in range(3, 8):                      # exhaustive agreement of the two formulas
    assert all(t_def(p) == t_fast(p) for p in itertools.permutations(range(1, n + 1)))
rng = random.Random(0)
for _ in range(10):
    p = list(range(1, 14)); rng.shuffle(p); assert t_def(p) == t_fast(p)
published = {3: 2, 4: 11, 5: 37, 6: 106, 7: 270, 8: 653, 9: 1523}   # Ahmed-Snevily
for n, v in published.items():
    assert max(t_fast(p) for p in itertools.permutations(range(1, n + 1))) == v

assert sorted(PI) == list(range(1, 18))
assert t_fast(PI) == TMAX17
assert t_def(PI) == TMAX17                 # straight from the definition, all 2^17 subsequences
sums = [PI[j] + PI[16 - j] for j in range(8)]
print('pair sums pi_j + pi_{18-j}, j=1..8:', sums)
bad = [(j + 1, s) for j, s in enumerate(sums) if s % 2 == 0]
assert bad, 'no violation'
print('t(pi) =', t_def(PI), '= tmax(17); even pair sums at j =', bad, '-> Odd Sum conjecture fails')
