import networkx as nx
import pandas as pd
from pyvis.network import Network
from urllib.parse import quote

# CSVファイルを読み込む
df = pd.read_csv("graph.csv")

# 新しい列を読み込む
color_column = df["理解度"].tolist()
print(color_column)

# ノード名、ノード番号、前提条件の列を抽出
nodes_data = df["単元名"].tolist()
node_numbers = df["単元番号"].tolist()
conditions = df["前単元"].tolist()

G = nx.DiGraph()  # 有向グラフに変更

# ノード名を変更するための辞書を作成
node_names = {node_numbers[i]: f"{node_numbers[i]} - {nodes_data[i]}" for i in range(len(node_numbers))}

# ノードを追加
for node_number, node_data in node_names.items():
    search_query = f'https://www.google.com/search?q={quote(nodes_data[node_numbers.index(int(node_number))]+"　小学")}'
    G.add_node(node_data, search_query=search_query)  # ノードに検索クエリを追加

# ノードの色を設定
color_mapping = {
    0: 'crimson',    # 整数に変更
    1: 'orange',     # 整数に変更
    2: 'khaki', 
    3: 'palegreen',  # 整数に変更
    4: 'forestgreen',  # 整数に変更
    5: 'deepskyblue',  # 整数に変更
}

# ノード間に逆向きの有向エッジ（逆向きの矢印）を作成
for i in range(len(nodes_data)):
    condition = conditions[i]
    if pd.isna(condition) or condition == '99999':
        # No dependencies (considering '99999' as no dependency)
        continue
    else:
        # Split conditions by ',' and create reversed directed edges to dependent nodes if they exist in the list
        dependent_nodes = condition.split(',')
        for dependent_node in dependent_nodes:
            dependent_node = int(dependent_node)
            if dependent_node in node_numbers:
                G.add_edge(node_names[dependent_node], node_names[node_numbers[i]])  # 逆向きのエッジを追加

# Create a Network instance
net = Network(notebook=True)

# Add nodes and directed edges to the network
for node in G.nodes:
    color = color_mapping.get(color_column[node_numbers.index(int(node.split(" - ")[0]))], 'gray')
    search_query = G.nodes[node].get('search_query', '')  # ノードの検索クエリを取得
    net.add_node(node, color=color, title=f'<a href="{search_query}" target="_blank">{node.split(" - ")[1]}</a>')

for edge in G.edges:
    net.add_edge(edge[0], edge[1], arrows='to')  # 'to' で矢印を有向エッジに設定

# Show the network graph
net.show('link_network.html')
