# Imports
from flask import Flask
from flask_session import Session

from dotenv import load_dotenv
from os import getenv as env, listdir
import logging, importlib


# Load env
load_dotenv()


# Create console log handler
console_log = logging.StreamHandler()
console_log.setFormatter(logging.Formatter("\033[1;32m%(asctime)s\033[0m - \033[1;34m%(levelname)s\033[0m - \033[1;31m%(name)s\033[0m - %(message)s"))
console_log.setLevel(logging.INFO)

# Create file log handler
file_log = logging.FileHandler(env('LOG_FILE', default='app.log'), mode=env('LOG_MODE', default='a'))
file_log.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s"))
file_log.setLevel(logging.DEBUG)

# Add handlers to the logger
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.addHandler(console_log)
log.addHandler(file_log)
log.info("Logging initialized")


# Create flask app
app = Flask(
    __name__,
    template_folder=env('TEMPLATE_FOLDER', default='../templates'),
    static_folder=env('STATIC_FOLDER', default='../static')
)

# Configure sessions
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


# Load routes
routes_dir = env('ROUTES_DIR', default='src/routes')
for filename in listdir(routes_dir):
    if not filename.endswith('.py') and filename.startswith('__'):
        continue

    module_name = f"{routes_dir.replace('/', '.')}.{filename[:-3]}"
    try:
        module = importlib.import_module(module_name)
        if hasattr(module, 'bp'):
            app.register_blueprint(module.bp)
            log.info(f"Registered blueprint: {module_name}")
    except Exception as e:
        log.error(f"Failed to register blueprint {module_name}: {e}")