import json
import networkx as nx
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
from app.services.agn_service.build_graph import build_graph
from app.services.agn_service.visualize_graph import visualize_graph

# Define the path to your index.json file
index_file_path = "graphs/index.json"  # Ensure this path is correct

# Function to load JSON data from file
def load_json_file(file_path):
    try:
        with open(file_path, "r") as file:
            return json.load(file)  # Parse JSON into a dictionary
    except json.JSONDecodeError as e:
        print(f"Error parsing JSON file: {e}")
        return None
    except FileNotFoundError:
        print(f"File not found: {file_path}")
        return None

# Load the JSON data
data = load_json_file(index_file_path)

# Check if data was loaded successfully
if data is None:
    print("Failed to load JSON data.")
else:
    # Build the graph using the loaded data
    try:
        G = build_graph(data)  # Pass the parsed JSON data (dictionary) to build_graph
        print("Graph built successfully.")
    except Exception as e:
        print(f"Error building graph: {e}")
        

output_image = "test_graph_visualization.png"

# Step 2: Generate and save the graph visualization
if G:
    visualize_graph(G, output_file=output_image)
    print(f"Graph visualization generated and saved as {output_image}")
else:
    print("Failed to build graph.")