from visualization import *
from parameters import *


def get_latest_file(directory):
    # List all files in the directory
    files = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

    # If there are no files, return None
    if not files:
        return None

    # Sort the files by modification time in descending order
    files.sort(key=lambda x: os.path.getmtime(x), reverse=True)

    # Return the latest file
    return files[0]

def is_number_str(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

graphs = ['karate']
for graph in graphs:
    g = graph_read(graph)
    task = "GD"
    paint_paras = painting_custimization(graph, task)
    communities = g.community_fastgreedy().as_clustering()
    Membership = communities.membership

    paint = PaintClass(g, graph, communities, paint_paras)
    LCC_list = []
    Removed_list = []
    repeat_counter = 0  # Initialize repeat counter

    image_path = f"Figure/GD/{graph}"
    clear_folder(image_path)
    for _ in range(10):
        g = graph_read(graph)
        paint.painting_GD_new(g)

        components = g.clusters()
        largest_component_size = max(components.sizes())

        LCCs = []
        removed_nodes = []
        original = True
        LCCs.append(largest_component_size)
        while len(removed_nodes) < g.vcount() * 0.25 - 1:
            result = invoke_with_image(query=prompt_GD, image_file=get_latest_file(image_path))
            if is_number_str(result) == False:
                print(result)
                print('error')
                continue
            print('node to remove:', result)
            node_remove = int(result)
            if node_remove in removed_nodes or node_remove > g.vcount() - 1:
                repeat_counter += 1  # Increment repeat counter
                if repeat_counter >= 10:  # Check if repeated 10 times
                    # Select the node with the largest degree
                    degrees = g.degree()
                    node_remove = max(range(len(degrees)), key=degrees.__getitem__)
                    print(f"Repeating too often, selecting largest degree node: {node_remove}")
                    repeat_counter = 0  # Reset the counter after removing the node
                else:
                    continue

            repeat_counter = 0  # Reset repeat counter after successful removal
            removed_nodes.append(node_remove)
            edges_to_remove = g.incident(node_remove)
            g.delete_edges(edges_to_remove)
            paint.painting_GD_new(g)
            components = g.connected_components()
            largest_component_size = max(components.sizes())
            print(f"Largest connected component size: {largest_component_size}")
            LCCs.append(largest_component_size)
        LCC_list.append(LCCs)
        Removed_list.append(removed_nodes)
