# api/__init__.py

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

load_dotenv()
app = Flask(__name__, static_folder='static', template_folder='templates')
app.wsgi_app = ProxyFix(app.wsgi_app)

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
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))

neo4j_logger = logging.getLogger('Neo4jLogger')
neo4j_logger.setLevel(logging.INFO)
neo4j_handler = logging.StreamHandler()
neo4j_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
neo4j_handler.setFormatter(neo4j_formatter)
neo4j_logger.addHandler(neo4j_handler)

app.neo4j_logger = neo4j_logger

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)

load_blueprints_from_directory('endpoints')

@app.route('/sitemap', methods=['GET'])
def sitemap():
    routes = []
    for rule in app.url_map.iter_rules():
        if rule.endpoint != 'sitemap':
            routes.append({
                'rule': rule.rule,
                'methods': list(rule.methods),
                'endpoint': rule.endpoint
            })
    return jsonify(routes)

@app.route('/render_member')
def render_member():
    return render_template('render_member.html')

@app.route('/render_network')
def render_network():
    return render_template('render_network.html')

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