from flask import Blueprint, request, jsonify
from app import get_driver, neo4j_logger

bp = Blueprint('nodes', __name__)

@bp.route('/nodes', methods=['GET', 'POST'])
def nodes():
    if request.method == 'GET':
        return get_nodes()
    elif request.method == 'POST':
        return create_node()

def get_nodes():
    node_type = request.args.get('type')
    if not node_type:
        return jsonify({"error": "Node type is required"}), 400

    filter_property = request.args.get('filter')
    driver = get_driver()

    try:
        with driver.session() as session:
            query = f"MATCH (n:{node_type}) RETURN n"
            neo4j_logger.info(f"Executing query: {query}")
            nodes = session.run(query)
            nodes_list = [
                {
                    'id': record['n'].id,
                    'labels': list(record['n'].labels),
                    **{key: value for key, value in record['n'].items()}
                }
                for record in nodes
            ]

        if filter_property:
            filtered_nodes_list = []
            for node in nodes_list:
                if filter_property in node:
                    filtered_nodes_list.append({filter_property: node[filter_property]})
            return jsonify({"nodes": filtered_nodes_list})

        return jsonify({"nodes": nodes_list})

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

def create_node():
    data = request.get_json()
    if not data:
        return jsonify({"error": "No data provided"}), 400

    node_type = data.pop('type', None)
    if not node_type:
        return jsonify({"error": "Node type is required in JSON data"}), 400

    properties = ', '.join([f'{key}: "${key}"' for key in data])
    query = f"CREATE (n:{node_type} {{{properties}}}) RETURN n"

    driver = get_driver()
    try:
        with driver.session() as session:
            neo4j_logger.info(f"Executing query: {query} with data: {data}")
            result = session.run(query, **data)

            new_node = {
                'id': result.single()['n'].id,
                'labels': list(result.single()['n'].labels),
                **{key: value for key, value in result.single()['n'].items()}
            }

        return jsonify(new_node), 201

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