"""Debug the chain DP: examine the structure of cut tires on a small
example to understand why R_i is empty.
"""
import os
import sys
import itertools
from collections import defaultdict

from sage.all import Graph, graphs

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from cut_depth_label import (
    parse_planar_code, HM_FILE, find_six_edge_cut,
    apply_procedure, compute_nice_layout,
)
from cut_tire_tree import build_tree
from tree_structure_sweep import all_six_edge_cuts


def examine_cut(G, cut_idx, max_cuts=10):
    cuts = all_six_edge_cuts(G, max_cuts=max_cuts)
    if cut_idx >= len(cuts):
        return
    S, cut_edges = cuts[cut_idx]
    base_pos = compute_nice_layout(G)
    S0 = S
    S1 = frozenset(G.vertices()) - S
    print(f'=== Cut #{cut_idx}: |S0|={len(S0)}, |S1|={len(S1)} ===')

    for side, S_side in [('0', S0), ('1', S1)]:
        print(f'\n--- Side {side} ---')
        try:
            H, pos, ed, _, _, _ = apply_procedure(
                G, S_side, cut_edges, base_pos, side,
                pendant_start_id=max(G.vertices()) + 1 +
                (0 if side == '0' else 200))
        except Exception as e:
            print(f'  apply failed: {e}')
            continue

        # Depth distribution
        from collections import Counter
        depth_count = Counter(ed.values())
        print(f'  edge depths: {dict(depth_count)}')
        print(f'  |H| = {H.order()} vertices, {H.size()} edges')
        print(f'  max depth: {max(ed.values()) if ed else "N/A"}')

        if not ed:
            continue
        faces_by_depth, parent_of, _ = build_tree(H, ed)
        for d in sorted(faces_by_depth.keys()):
            faces = faces_by_depth[d]
            print(f'  H_{d}: {len(faces)} faces')
            for f_idx, face in enumerate(faces[:3]):
                verts = set()
                for u, v in face:
                    verts.add(u)
                    verts.add(v)
                # For each vertex, count incident H edges
                bdry_v_data = []
                for v in verts:
                    incident = list(H.neighbors(v))
                    incident_depths = [ed[tuple(sorted((v, nb)))]
                                       for nb in incident]
                    bdry_v_data.append((v, incident_depths))
                # Show first few
                print(f'    face {f_idx}: |bdry|={len(face)}, '
                      f'verts={len(verts)}, sample: {bdry_v_data[:3]}')


def main():
    G = graphs.DodecahedralGraph()
    G.is_planar(set_embedding=True)
    examine_cut(G, cut_idx=2, max_cuts=5)


if __name__ == '__main__':
    main()
