import os
from dash import Dash
import dash_bootstrap_components as dbc

from bfabric_web_apps.utils.config import settings


def create_app(title=None, url_base_pathname=None, assets_folder='assets'):
    """
    Initialize and return a Dash app instance.

    Args:
        title (str, optional): The browser tab title.
            Defaults to APP_TITLE from .env settings.
        url_base_pathname (str, optional): The base pathname for the app (e.g., '/lfu/').
            If not provided, reads from SCRIPT_NAME environment variable.
            Must start and end with '/'.
        assets_folder (str, optional): Path to assets folder.
            Defaults to 'assets' relative to caller.

    Returns:
        Dash: Configured Dash application instance.
    """
    # Get URL base pathname from parameter, settings, or environment variable
    if url_base_pathname is None:
        # Try settings first (from .env), then fall back to environment variable
        script_name = settings.SCRIPT_NAME or os.getenv('SCRIPT_NAME', '')
        if script_name:
            url_base_pathname = script_name if script_name.endswith('/') else script_name + '/'

    # Prepare Dash kwargs
    dash_kwargs = {
        'title': title or settings.APP_TITLE,
        'suppress_callback_exceptions': True,  # Allow dynamic callbacks
        'external_stylesheets': [dbc.themes.BOOTSTRAP],
        'meta_tags': [{"name": "viewport", "content": "width=device-width, initial-scale=1.0"}],
        'assets_folder': assets_folder,
    }

    # Add URL prefix if specified
    if url_base_pathname:
        dash_kwargs['requests_pathname_prefix'] = url_base_pathname
        dash_kwargs['routes_pathname_prefix'] = url_base_pathname

    return Dash(__name__, **dash_kwargs)
