from flask import Blueprint, Flask, render_template
from flask_login import login_required
from models import SiteSettings
import os

def init_app(app: Flask):
    # Create blueprints
    main_bp = Blueprint('main', __name__)
    auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
    rooms_bp = Blueprint('rooms', __name__)

    # Import and initialize routes
    from .main import init_routes as init_main_routes
    from .auth import init_routes as init_auth_routes
    from .contacts import contacts_bp as contacts_routes
    from .rooms import rooms_bp as rooms_routes
    from .conversations import conversations_bp as conversations_routes
    from .admin import admin as admin_routes
    from .email_templates import email_templates as email_templates_routes
    from .user import user_bp as user_routes

    # Initialize routes
    init_main_routes(main_bp)
    init_auth_routes(auth_bp)

    # Add site_settings context processor to all blueprints
    @app.context_processor
    def inject_site_settings():
        site_settings = SiteSettings.query.first()
        return dict(site_settings=site_settings)

    # Add MASTER environment variable to all templates
    @app.context_processor
    def inject_master():
        return dict(is_master=os.environ.get('MASTER', 'false').lower() == 'true')

    # Register blueprints
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(rooms_routes)
    app.register_blueprint(contacts_routes)
    app.register_blueprint(conversations_routes)
    app.register_blueprint(admin_routes)
    app.register_blueprint(email_templates_routes)
    app.register_blueprint(user_routes)

    @app.route('/rooms/<int:room_id>/trash')
    @login_required
    def trash_page(room_id):
        return render_template('trash/trash.html')

    return app

# This file makes the routes directory a Python package 