# endpoints/person_network.py

from flask import Blueprint, jsonify
import neo4j
from neo4j import GraphDatabase
from app import get_driver, neo4j_logger

bp = Blueprint('network', __name__)

@bp.route('/person_network', methods=['GET'])
def person_network():
    driver = get_driver()

    try:
        with driver.session() as session:
            query = """
            MATCH (p:Person)-[r]->(n)
            RETURN p, r, n
            """
            result = session.run(query)

            nodes = {}
            links = []

            for record in result:
                person_node = record['p']
                relationship = record['r']
                connected_node = record['n']

                # Add Person node if not already added
                person_id = person_node.id
                if person_id not in nodes:
                    properties = {key: value for key, value in person_node.items()}
                    properties['id'] = person_id
                    properties['labels'] = list(person_node.labels)  # Include labels separately
                    nodes[person_id] = {
                        **properties,
                        "group": 1  # Group for Person
                    }

                # Add connected node if not already added
                connected_id = connected_node.id
                if connected_id not in nodes:
                    properties = {key: value for key, value in connected_node.items()}
                    properties['id'] = connected_id
                    properties['labels'] = list(connected_node.labels)  # Include labels separately
                    nodes[connected_id] = {
                        **properties,
                        "group": 2  # Group for other nodes (e.g., Organization, Position)
                    }

                # Add link
                links.append({
                    "source": person_id,
                    "target": connected_id,
                    "type": relationship.type,
                    "rel_properties": {key: value for key, value in relationship.items()}
                })

        return jsonify({"nodes": list(nodes.values()), "links": links})

    except Exception as e:
        print(f"Error interacting with Neo4j: {e}")
        return jsonify({"error": f"An error occurred while interacting with the database: {str(e)}"}), 500
