# Imports
from flask import Blueprint, render_template, abort
import os, importlib, logging


# Logging
log = logging.getLogger("__main__")


# Create blueprint
bp = Blueprint('dynamic', __name__)
template_folder = "templates"


# helper func
def get_path(file) -> str:
    return os.path.join(template_folder, "pages", file)


# Get all files in folder
def ListFiles(path):
    path = get_path(path)
    files = []
    for root, dirs, files_in_dir in os.walk(path):
        for file in files_in_dir:
            files.append(os.path.relpath(os.path.join(root, file), path))
        for dir in dirs:
            files.append(os.path.relpath(os.path.join(root, dir), path) + '/')
    return files


# Import handlers
handlers_unloaded = os.listdir("src/handlers")
handlers_unloaded = [handler for handler in handlers_unloaded if handler.endswith(".py")]
handlers = {}

for handler in handlers_unloaded:
    try:
        try: module = importlib.import_module(f'src.handlers.{handler[:-3]}')
        except ImportError: module = importlib.import_module(f'handlers.{handler[:-3]}')
        handlers[handler[:-3]] = module.callback
        log.info(f"Loaded handler {handler}: {module.callback}")

    except Exception as e:
        log.error(f"Failed to load handler {handler}: {e}")
        continue


# Catch-all route for generic pages
@bp.route('/<path:filename>')
def catch_all(filename):
    if os.path.exists(get_path(filename)):
        if os.path.isdir(get_path(filename)):
            return render_template(
                'bases/directory.html',
                directory=filename + "/" if not filename.endswith('/') else filename,
                pages=ListFiles(filename)
            )
        
        if filename.split('.')[-1] in handlers.keys():
            return handlers[filename.split('.')[-1]](filename)
        
        return render_template(f'pages/{filename}')

    elif os.path.exists(get_path(filename + '.html')):
        return render_template(f'pages/{filename}.html')

    else:
        for ext in handlers.keys():
            if os.path.exists(get_path(filename + f".{ext}")):
                return handlers[ext](filename + f".{ext}")

        abort(404, f"'{filename}' not found")