"""Verify: across all 1,314 bad chord-apex+Kempe colourings, does
at least one G'-pentagon (length 5) have its boundary entirely in
V(K_b) ∪ V(K_c)?

(Earlier characterize_S_vertices.py and check_30_residual_v2.py
suggested yes, but let's verify directly.)

This is the G'-pentagon fallback conjecture for the empirically
identified bad cases.

Run with: sage experiments/check_gprime_pentagon_always_works.py
"""
import os
import sys
import time

from sage.all import Graph
from sage.graphs.graph_generators import graphs

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

from check_conj_final_scaled import (
    apply_reduction,
    proper_3_edge_colorings,
    matches_chord_apex_kempe,
    kempe_cycle_set,
    edge_idx,
)
from check_heawood_on_kempe import dual_of, vertices_of_kempe


def test_one(D):
    D.is_planar(set_embedding=True)
    bad_count = 0
    bad_with_uncov_pent = 0
    examples_no_uncov = []
    for face in D.faces():
        if len(face) != 5: continue
        for i_red in range(5):
            res = apply_reduction(D, face, i_red, 9999)
            if res is None: continue
            H = res['H']; named = res['named']
            H.is_planar(set_embedding=True)
            edges, colorings = proper_3_edge_colorings(H)
            cand = [c for c in colorings
                    if matches_chord_apex_kempe(edges, c, named)]
            v_n = 9999
            for col in cand:
                target = {named['side_0'], named['spike']}
                lower_flank = None
                for f in H.faces():
                    if target.issubset({frozenset(e) for e in f}):
                        lower_flank = f; break
                if lower_flank is None or len(lower_flank) != 5: continue
                arc_verts = [e[0] for e in lower_flank]
                if v_n not in arc_verts: continue
                k = arc_verts.index(v_n)
                cyc = arc_verts[k:] + arc_verts[:k]
                A_i = next(iter(named['side_0'] - {v_n}))
                A_ip1 = next(iter(named['spike'] - {v_n}))
                if cyc[1] == A_i and cyc[4] == A_ip1:
                    P_1, P_2 = cyc[2], cyc[3]
                elif cyc[1] == A_ip1 and cyc[4] == A_i:
                    P_2, P_1 = cyc[2], cyc[3]
                else: continue
                merged_idx = edge_idx(edges, named['merged'])
                c_col = col[merged_idx]
                c_0_col = col[edge_idx(edges, named['side_0'])]
                c_1_col = col[edge_idx(edges, named['side_1'])]
                e_AiP1 = edge_idx(edges, frozenset((A_i, P_1)))
                e_P1P2 = edge_idx(edges, frozenset((P_1, P_2)))
                if e_AiP1 is None or e_P1P2 is None: continue
                if col[e_AiP1] != c_1_col or col[e_P1P2] != c_0_col:
                    continue
                a = c_col
                other = [x for x in range(3) if x != a]
                kc_b = kempe_cycle_set(edges, col, merged_idx, (a, other[0]))
                kc_c = kempe_cycle_set(edges, col, merged_idx, (a, other[1]))
                V_b = vertices_of_kempe(edges, kc_b)
                V_c = vertices_of_kempe(edges, kc_c)
                V_union = V_b | V_c
                S = set(H.vertices()) - V_union
                if P_1 in V_union: continue
                bad_count += 1
                # Search for an UNCOVERED G'-pentagon
                found_uncov_pent = False
                for f in H.faces():
                    if len(f) != 5: continue
                    fset = {frozenset(e) for e in f}
                    # Must be G'-pentagon (not adjacent to F_v reduction)
                    if (named['side_0'] in fset or named['side_1'] in fset
                        or named['spike'] in fset or named['merged'] in fset):
                        continue
                    verts = {u for (u, v) in f} | {v for (u, v) in f}
                    if verts.issubset(V_union):
                        found_uncov_pent = True
                        break
                if found_uncov_pent:
                    bad_with_uncov_pent += 1
                else:
                    if len(examples_no_uncov) < 3:
                        examples_no_uncov.append({
                            'S_size': len(S),
                        })
    return bad_count, bad_with_uncov_pent, examples_no_uncov


def main(max_n=20, time_budget_per_n=1800):
    print("Direct check: G'-pentagon fallback on bad colourings.\n")
    grand_bad = 0
    grand_with = 0
    grand_ex = []
    for n in range(12, max_n + 1):
        start = time.time()
        try:
            triangulations = list(graphs.triangulations(n, minimum_degree=5))
        except Exception as ex:
            print(f"n={n}: cannot enumerate ({ex})")
            continue
        n_bad = 0; n_with = 0
        for tri_idx, G in enumerate(triangulations):
            if time.time() - start > time_budget_per_n:
                print(f"  n={n}: timeout")
                break
            G.is_planar(set_embedding=True)
            D = dual_of(G)
            nb, nw, exs = test_one(D)
            n_bad += nb; n_with += nw
            grand_ex.extend(exs)
        elapsed = time.time() - start
        print(f"n={n}: {n_bad} bad, {n_with} with uncovered G'-pentagon "
              f"[{elapsed:.0f}s]")
        sys.stdout.flush()
        grand_bad += n_bad
        grand_with += n_with
    print()
    print("=" * 70)
    print(f"Total bad colourings: {grand_bad}")
    print(f"With at least one uncovered G'-pentagon: {grand_with} "
          f"({100*grand_with/max(grand_bad, 1):.2f}%)")
    if grand_bad - grand_with > 0:
        print(f"WITHOUT uncovered G'-pentagon: {grand_bad - grand_with}")
        print("Examples:")
        for ex in grand_ex:
            print(f"  |S| = {ex['S_size']}")


if __name__ == '__main__':
    main()
