"""Inspect one Phase 2 failure to see why an odd cycle survived."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import networkx as nx
from collections import defaultdict
from triangulation_gen import enumerate_all_triangulations
from level_cycles import compute_levels
from depth_monovariant_check import (
    faces_of_subgraph, canonical_face, edges_of_face,
    apex_levels_for_edge, identify_outer_face, face_depths,
    tricky_odd_faces, lowest_depth_neighbor_flip,
)
from full_resolution_check import (
    phase1_resolve_tricky, phase2_flip_outer_incident, is_Lk_bipartite,
)


tris = enumerate_all_triangulations(10)
G = tris[13]
source_set = {1, 2, 4}
levels = compute_levels(G, source_set)
by_level = defaultdict(list)
for v, lv in levels.items():
    by_level[lv].append(v)
nodes_k = by_level[1]
k = 1

print("INITIAL G")
print(f"  L_1 = {sorted(nodes_k)}")
Lk0 = G.subgraph(nodes_k)
print(f"  L_1 edges: {sorted(Lk0.edges())}")
print(f"  L_1 bipartite? {nx.is_bipartite(Lk0)}")

print("\nRunning Phase 1...")
G1, emb1, p1_steps, p1_reason = phase1_resolve_tricky(G, levels, nodes_k, k)
print(f"  Phase 1: {p1_steps} steps, reason={p1_reason}")
Lk1 = G1.subgraph(nodes_k)
print(f"  L_1 after Phase 1: edges = {sorted(Lk1.edges())}")
print(f"  L_1 bipartite? {nx.is_bipartite(Lk1)}")

faces = faces_of_subgraph(G1, emb1, nodes_k)
outer = identify_outer_face(faces, G1, emb1, levels, k)
outer_face = next(f for f in faces if canonical_face(f) == outer)
print(f"\n  outer face: {outer_face}")
print(f"  faces of L_1:")
outer_edges = set(frozenset(list(e)) for e in edges_of_face(outer_face))
for f in faces:
    cf = canonical_face(f)
    if cf == outer:
        continue
    incident = any(frozenset([a, b]) in outer_edges
                   for (a, b) in edges_of_face(f))
    odd = len(f) % 2 == 1
    print(f"    {f}: len={len(f)} odd={odd} incident_to_outer={incident}")

# Enumerate ALL simple cycles of L_1 (not just face-cycles)
print(f"\n  all simple cycles of L_1 (up to length 6):")
def find_cycles(G, max_len):
    cycles = set()
    for u in G.nodes():
        for v in G.neighbors(u):
            for path in nx.all_simple_paths(G, v, u, cutoff=max_len-1):
                if len(path) >= 3:
                    c = tuple(sorted(path))
                    cycles.add(c)
    return cycles
for cyc in sorted(find_cycles(Lk1, 6)):
    if len(cyc) % 2 == 1:
        print(f"    {cyc} (odd, len {len(cyc)})")

print("\nRunning Phase 2...")
G2, flips = phase2_flip_outer_incident(G1, emb1, levels, nodes_k, k)
print(f"  flips: {flips}")
Lk2 = G2.subgraph(nodes_k)
print(f"  L_1 after Phase 2: edges = {sorted(Lk2.edges())}")
print(f"  L_1 bipartite? {nx.is_bipartite(Lk2)}")
print(f"\n  all odd simple cycles of final L_1 (up to length 6):")
for cyc in sorted(find_cycles(Lk2, 6)):
    if len(cyc) % 2 == 1:
        print(f"    {cyc}")
