"""Independent check of the octahedron-exclusion lemma behind the Erdős #579 disproof
(claim IIS-C-2196, conjectures.io result e4934265).

Setting: G is a "two-part graph" on A ⊔ B.  Inside A the edges are GA, inside B
they are GB, and a cross pair (a, b) is an edge iff M(label a, label b).
Hypotheses of the lemma (Lean: Er579.twoPartGraph_octahedron_free):
  (T) GA, GB triangle-free;  (C) GA, GB contain no 4-cycle;
  (P) for every GA-edge a-u, and every two GB-edges b-w, b-z with w != z,
      NOT (a~w, a~z, u~b, u~w, u~z all cross edges)        [the "5-edge exclusion"]
      (the Lean statement phrases this through labels; this is the
       label-free consequence actually used).
Claim: G contains no (not necessarily induced) octahedron K_{2,2,2}.

Check 1 (exhaustive, this script): for every map of the 6 octahedron vertices to
the sides {A, B}, the edges of K_{2,2,2} that land inside one side contain a
triangle or a 4-cycle, or the map has the pattern used in (P), up to swapping
A and B.  Note that (P) is not symmetric in A and B: the Lean lemma has to
place the "two leaves" side on B.  The script also checks whether the pattern
can always be oriented that way, i.e. whether every map with no monochromatic
triangle or C4 has the (P)-pattern with the leaves w, z in B.

Check 2 (exhaustive on small random instances): build random two-part graphs
satisfying (T), (C) and (P), and search them directly for a K_{2,2,2}
subgraph by brute force.
"""
import itertools
import random

# Octahedron: vertices (part, idx), part in 0..2, idx in 0..1; adjacent iff parts differ.
V = [(p, i) for p in range(3) for i in range(2)]
def adj(x, y):
    return x[0] != y[0]

def mono_triangle(side):
    for x, y, z in itertools.combinations(V, 3):
        if adj(x, y) and adj(y, z) and adj(x, z) and side[x] == side[y] == side[z]:
            return True
    return False

def mono_c4(side):
    # 4-cycle x-y-z-w-x with x != z, y != w, all four on one side
    for quad in itertools.permutations(V, 4):
        x, y, z, w = quad
        if side[x] == side[y] == side[z] == side[w] and adj(x, y) and adj(y, z) and adj(z, w) and adj(w, x):
            return True
    return False

def pattern(side, leaves_side):
    """Pattern P with the two leaves w, z on `leaves_side` and a, u on the other side:
    distinct parts i, j, k; u in part i on the other side; both vertices of part j
    (w, z) on leaves_side; part k split: a on the other side, b on leaves_side.
    Then a-u is an edge inside the other side, b-w and b-z inside leaves_side,
    and a-w, a-z, u-b, u-w, u-z are cross edges."""
    other = 1 - leaves_side
    for i, j, k in itertools.permutations(range(3), 3):
        us = [x for x in V if x[0] == i and side[x] == other]
        if not us:
            continue
        if not all(side[(j, t)] == leaves_side for t in range(2)):
            continue
        ks = [side[(k, t)] for t in range(2)]
        if sorted(ks) == [0, 1]:
            return True
    return False

def check1():
    bad = []
    oriented_ok = True
    for bits in itertools.product([0, 1], repeat=6):
        side = dict(zip(V, bits))
        if mono_triangle(side) or mono_c4(side):
            continue
        p_B = pattern(side, 1)   # leaves on side 1 = B
        p_A = pattern(side, 0)
        if not (p_A or p_B):
            bad.append(bits)
        if not p_B:
            oriented_ok = False
    return bad, oriented_ok

def has_k222(n, E):
    """Brute-force search for a (non-induced) K_{2,2,2} in graph on range(n)."""
    nbr = [set() for _ in range(n)]
    for u, v in E:
        nbr[u].add(v); nbr[v].add(u)
    for six in itertools.combinations(range(n), 6):
        # try all ways to split six into 3 unordered pairs
        a = six[0]
        rest = six[1:]
        for b in rest:
            r2 = [x for x in rest if x != b]
            c = r2[0]
            for d in r2[1:]:
                e, f = [x for x in r2 if x not in (c, d)]
                parts = [(a, b), (c, d), (e, f)]
                ok = True
                for P, Q in itertools.combinations(parts, 2):
                    for x in P:
                        for y in Q:
                            if y not in nbr[x]:
                                ok = False; break
                        if not ok: break
                    if not ok: break
                if ok:
                    return True
    return False

def triangle_free(n, E):
    s = set(map(frozenset, E))
    return not any({frozenset((x, y)), frozenset((y, z)), frozenset((x, z))} <= s
                   for x, y, z in itertools.combinations(range(n), 3))

def c4_free(n, E):
    s = set(map(frozenset, E))
    for x, y, z, w in itertools.permutations(range(n), 4):
        if x < z and y < w and x < y:  # weak symmetry reduction
            if {frozenset((x, y)), frozenset((y, z)), frozenset((z, w)), frozenset((w, x))} <= s:
                return False
    return True

def check2(trials=400, nA=5, nB=5, seed=579):
    rng = random.Random(seed)
    found_counter = 0
    tested = 0
    for _ in range(trials):
        A = list(range(nA)); B = list(range(nA, nA + nB))
        EA = [e for e in itertools.combinations(A, 2) if rng.random() < 0.5]
        EB = [e for e in itertools.combinations(B, 2) if rng.random() < 0.5]
        if not (triangle_free(nA + nB, EA) and c4_free(nA + nB, EA)
                and triangle_free(nA + nB, EB) and c4_free(nA + nB, EB)):
            continue
        X = {(a, b) for a in A for b in B if rng.random() < 0.7}
        sA = set(map(frozenset, EA)); sB = set(map(frozenset, EB))
        # enforce (P) by deleting cross edges until no violation remains
        changed = True
        while changed:
            changed = False
            for a, u in itertools.permutations(A, 2):
                if frozenset((a, u)) not in sA: continue
                for b in B:
                    nb = [w for w in B if frozenset((b, w)) in sB]
                    for w, z in itertools.permutations(nb, 2):
                        need = [(a, w), (a, z), (u, b), (u, w), (u, z)]
                        if all(p in X for p in need):
                            X.discard(rng.choice(need)); changed = True
        E = EA + EB + list(X)
        tested += 1
        if has_k222(nA + nB, E):
            found_counter += 1
    return tested, found_counter

if __name__ == "__main__":
    # self-test of the brute-force search: K_{2,2,2} itself, and K_{2,2,2} minus an edge
    oct_E = [(2 * p + i, 2 * q + j) for p in range(3) for q in range(p + 1, 3) for i in range(2) for j in range(2)]
    assert has_k222(6, oct_E) and not has_k222(6, oct_E[1:])
    bad, oriented_ok = check1()
    print("check1: colourings with no mono triangle/C4 and no pattern:", bad)
    print("check1: every such colouring has the pattern with leaves on B:", oriented_ok)
    tested, found = check2()
    print(f"check2: {tested} random instances satisfying (T),(C),(P); K222 found in {found}")
    assert not bad and found == 0
