# endpoints/create_sponsored_relationship.py

from flask import Blueprint, jsonify
from neo4j import GraphDatabase
import logging
from app import get_driver, neo4j_logger  # Use absolute import

bp = Blueprint('create_sponsored_relationship', __name__)

@bp.route('/create_sponsored_relationship', methods=['GET'])
def create_sponsored_relationship():
    try:
        driver = get_driver()
        with driver.session() as session:
            # Step 3: Implement the endpoint logic
            legislation_nodes = session.run("MATCH (l:Legislation) RETURN l")
            for record in legislation_nodes:
                legislation = record['l']
                bioguide_id = legislation.get('sponsored_by')

                if bioguide_id:
                    person_node = session.run(
                        "MATCH (p:Person {bioguideId: $bioguideId}) RETURN p",
                        {"bioguideId": bioguide_id}
                    ).single()

                    if person_node:
                        person = person_node['p']
                        session.run(
                            "MATCH (p:Person), (l:Legislation) "
                            "WHERE id(p) = $person_id AND id(l) = $legislation_id "
                            "CREATE (p)-[:SPONSORED]->(l)",
                            {"person_id": person.id, "legislation_id": legislation.id}
                        )
                        neo4j_logger.info(f"Created SPONSORED relationship from Person {person['name']} to Legislation {legislation['title']}")
                    else:
                        neo4j_logger.warning(f"No Person node found for bioguideId: {bioguide_id}")

            return jsonify({"status": "success", "message": "SPONSORED relationships created successfully"}), 201

    except Exception as e:
        neo4j_logger.error(f"Error creating SPONSORED relationships: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500
