import csv
import json
import networkx as nx
import matplotlib.pyplot as plt

def csv_to_json(csv_file_path, json_file_path, fields=None):
    """
    Convert a CSV file to JSON format.

    Parameters:
    - csv_file_path (str): Path to the input CSV file.
    - json_file_path (str): Path to save the output JSON file.
    - fields (list of str, optional): List of fields to include in the JSON.
      If None, all fields from the CSV will be included.

    """
    # Read CSV file and convert to JSON
    with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        
        # Filter fields if specified
        if fields:
            data = [{field: row[field] for field in fields} for row in csv_reader]
        else:
            data = [row for row in csv_reader]
        
        # Write JSON data to file
        with open(json_file_path, mode='w', encoding='utf-8') as json_file:
            json.dump(data, json_file, indent=4, ensure_ascii=False)
    
    print(f"CSV 数据已成功转换为 JSON 格式并保存为 {json_file_path}")
    return data

def proecess_relation(csv_path,json_path):
# Example usage for relation.csv
    relation_data=csv_to_json(csv_path,json_path)
    return relation_data

def proecess_entity(csv_path,json_path):
    entity_fields = ["entity name", "entity type", "timestamp", "description"]
    entity_data=csv_to_json(csv_path,json_path, fields=entity_fields)
    return entity_data

def json_graph(csv_path,json_path):
    entities_csv_path=csv_path / "entity.csv"
    entities_json_path=json_path / "entity.json"
    
    entities = proecess_entity(entities_csv_path,entities_json_path)

    relations_csv_path=csv_path / "relation.csv"
    relations_json_path=json_path / "relation.json"

    relations = proecess_relation(relations_csv_path,relations_json_path)

    # 创建有向图
    G = nx.DiGraph()


    # 向图中添加实体节点
    for entity in entities:
        node = entity["entity name"]
        # 可以在节点属性中存储实体类型、时间戳、描述等信息
        G.add_node(node, 
                entity_type=entity.get("entity type"),
                timestamp=entity.get("timestamp"),
                description=entity.get("description"))

    # 向图中添加关系边
    for relation in relations:
        entity1 = relation["entity1"]
        entity2 = relation["entity2"]
        rel_type = relation["relation"]
        
        # 添加边并设置边的属性，如关系类型和描述
        G.add_edge(entity1, entity2, relation=rel_type)
    return G

