# endpoints/store_sponsors.py
from flask import Blueprint, jsonify
from app import get_driver, neo4j_logger
import json
import os

bp = Blueprint('store_sponsors', __name__)

CACHE_FILE = 'cache.json'

def load_cache():
    if os.path.exists(CACHE_FILE):
        with open(CACHE_FILE, 'r') as f:
            return json.load(f)
    return {}

def save_cache(cache_data):
    with open(CACHE_FILE, 'w') as f:
        json.dump(cache_data, f)

@bp.route('/store_sponsors')
def store_sponsors():
    cache = load_cache()

    if 'bioguideIds' in cache and len(cache['bioguideIds']) > 0:
        return jsonify({"message": "bioguideIds already cached"}), 200

    driver = get_driver()
    with driver.session() as session:
        query = "MATCH (n:Person) RETURN n.bioguideId"
        neo4j_logger.info(f"Executing query: {query}")

        # Fetch the records
        records = session.run(query)

        bioguideIds = []

        for record in records:
            bioguideId = record['n.bioguideId']
            if bioguideId is not None:
                bioguideIds.append(bioguideId)
                print(f"Storing bioguideId: {bioguideId}")  # Print each bioguideId as it's added
            else:
                print("Found a record with None bioguideId")  # Log any None values

        cache['bioguideIds'] = bioguideIds

        neo4j_logger.info(f"Cached bioguideIds: {len(bioguideIds)}")

    # Save the updated cache
    save_cache(cache)

    return jsonify({"message": "bioguideIds cached successfully", "cached_bioguideIds_count": len(cache['bioguideIds'])}), 200
