# endpoints/create_cosponsored_relationship.py

from flask import Blueprint, jsonify
import logging
import csv
import os
from neo4j import GraphDatabase
from app import get_driver, neo4j_logger  # Ensure relative imports work

bp = Blueprint('create_cosponsored_relationship', __name__)

@bp.route('/create_cosponsored_relationship', methods=['GET'])
def create_cosponsored_relationship():
    try:
        # Path to the CSV file
        csv_file_path = os.path.join(os.path.dirname(__file__), '..', 'cosponsored_legislation.csv')

        if not os.path.exists(csv_file_path):
            return jsonify({"status": "error", "message": "CSV file not found"}), 404

        driver = get_driver()
        with driver.session() as session:
            # Read the CSV data
            with open(csv_file_path, mode='r', newline='', encoding='utf-8') as csv_file:
                csv_reader = csv.DictReader(csv_file)

                for row in csv_reader:
                    cosponsored_by = row.get('cosponsored_by')
                    number = row.get('number')

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

                        legislation_node = session.run(
                            "MATCH (l:Legislation {number: $number}) RETURN l",
                            {"number": number}
                        ).single()

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

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

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