from flask import Blueprint, jsonify
import json
import os
import logging
from neo4j import GraphDatabase
from dotenv import load_dotenv


bp = Blueprint('create_legislation_node', __name__)


@bp.route('/create_legislation_node', methods=['GET'])
def create_legislation_nodes():
    # Assuming the legislation cache is stored in a JSON file
    legislation_cache_path = os.getenv("LEGISLATION_CACHE_PATH")

    if not legislation_cache_path:
        return jsonify({"error": "Legislation cache path is not set"}), 400

    try:
        with open(legislation_cache_path, 'r') as f:
            legislation_data = json.load(f)
    except FileNotFoundError:
        return jsonify({"error": "Legislation cache file not found"}), 404
    except json.JSONDecodeError:
        return jsonify({"error": "Failed to decode JSON from the legislation cache"}), 500

    # Ensure legislation_data is a list of dictionaries
    if not isinstance(legislation_data, list):
        return jsonify({"error": "Legislation data should be a list"}), 400

    created_nodes = []

    for item in legislation_data:
        if not item.get("id"):
            continue

        # Prepare the properties for the node
        properties = {k: v for k, v in item.items()}

        # Create or merge a node in Neo4j with all properties
        driver = get_driver()
        with driver.session() as session:
            query = "MERGE (l:Legislation {id: $id})"
            for key in properties:
                if key != 'id':
                    query += f" ON CREATE SET l.{key} = ${key}"

            result = session.run(query, **properties)

            # Log the creation or merging of the node
            neo4j_logger.info(f"Created/Merged Legislation node with ID: {item.get('id')} and properties: {properties}")

        driver.close()

        created_nodes.append({"id": item.get("id"), "properties": properties})

    return jsonify({"message": "Legislation nodes created/merged successfully", "nodes": created_nodes}), 201
