# endpoints/relationships.py
from flask import Blueprint, request, jsonify
from app import get_driver, neo4j_logger

bp = Blueprint('relationships', __name__)

@bp.route('/relationships', methods=['GET', 'POST'])
def relationships():
    if request.method == 'GET':
        relationship_type = request.args.get('type')

        if not relationship_type:
            return list_relationship_types()
        else:
            return list_relationships_by_type(relationship_type)
    elif request.method == 'POST':
        return create_relationship()

def list_relationship_types():
    driver = get_driver()
    with driver.session() as session:
        query = "CALL db.relationshipTypes()"
        neo4j_logger.info(f"Executing query: {query}")
        result = session.run(query)

        # Convert the result to a list of dictionaries
        relationship_types_list = [record['relationshipType'] for record in result]

    return jsonify({"relationship_types": relationship_types_list})

def list_relationships_by_type(relationship_type):
    driver = get_driver()
    with driver.session() as session:
        query = f"MATCH ()-[r:{relationship_type}]->() RETURN r"
        neo4j_logger.info(f"Executing query: {query}")
        relationships = session.run(query)

        # Convert the relationships to a list of dictionaries
        relationships_list = [
            {
                'id': record['r'].id,
                'type': relationship_type,
                **{key: value for key, value in record['r'].items()}
            }
            for record in relationships
        ]

    return jsonify({"relationships": relationships_list})

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

    required_keys = ['start_node_id', 'end_node_id', 'type']
    for key in required_keys:
        if key not in data:
            return jsonify({"error": f"Missing required field: {key}"}), 400

    start_node_id = data['start_node_id']
    end_node_id = data['end_node_id']
    relationship_type = data['type']

    # Optional properties
    properties = ', '.join([f'{key}: "${key}"' for key in data if key not in required_keys])
    property_clause = f"{{{properties}}}" if properties else ""

    query = f"MATCH (a) WHERE id(a)={start_node_id} MATCH (b) WHERE id(b)={end_node_id} CREATE (a)-[r:{relationship_type}{property_clause}]->(b) RETURN r"

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

        # Convert the created relationship to a dictionary
        new_relationship = {
            'id': result.single()['r'].id,
            'type': relationship_type,
            **{key: value for key, value in result.single()['r'].items()}
        }

    return jsonify(new_relationship), 201
