# Imports
from flask import Blueprint, render_template, request, abort, send_from_directory
from os import getenv as env
import logging


# Create blueprint
bp = Blueprint(
    'generic',
    __name__,
    template_folder=env('TEMPLATE_FOLDER', default='../templates'),
    static_folder=env('STATIC_FOLDER', default='../static')
)


# Create logger
log = logging.getLogger(__name__)


# Route for index page
@bp.route('/')
def index():
    return render_template('index.html')


# Route for robots.txt, sitemap.xml, and favicon.ico
@bp.route('/robots.txt')
@bp.route('/sitemap.xml')
@bp.route('/favicon.ico')
def web_stuffs():
    return send_from_directory(
        env('STATIC_FOLDER', default='../static'),
        request.path.lstrip('/')
    )


# catch-all route for any other static pages (only in root path)
@bp.route('/<string:filename>')
def static_files(filename):
    try:
        return render_template(filename if filename.endswith('.html') else filename + '.html')
    except Exception as e:
        log.error(f"Error serving static file {filename}: {e}")
        abort(404)