# app.py
from flask import Flask, jsonify, request
import os
import logging
from neo4j import GraphDatabase
from dotenv import load_dotenv
from werkzeug.middleware.proxy_fix import ProxyFix
import importlib.util

load_dotenv()

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Neo4j configuration
NEO4J_URI = os.getenv("NEO4J_URI")
NEO4J_USER = os.getenv("NEO4J_USER")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")

def get_driver():
    return GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))

# Function to dynamically import and register blueprints
def load_blueprints_from_directory(directory):
    for filename in os.listdir(directory):
        if filename.endswith('.py') and not filename.startswith('__'):
            module_name = filename[:-3]  # Remove .py extension
            file_path = os.path.join(directory, filename)

            spec = importlib.util.spec_from_file_location(module_name, file_path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)

            if hasattr(module, 'bp'):
                app.register_blueprint(module.bp)
                logging.info(f'Registered blueprint: {module.bp.name}')

# Load blueprints from the endpoints directory
load_blueprints_from_directory(os.path.join(os.path.dirname(__file__), 'endpoints'))

@app.route('/')
def index():
    return jsonify({"message": "Welcome to the Flask API!"})

if __name__ == '__main__':
    app.run(debug=True)
