from ahserver.webapp import webapp
from ahserver.serverenv import ServerEnv
import os

# Import required modules using the standard pattern
# Foundation modules
from appbase.init import load_appbase
from rbac.init import load_rbac

# Business modules
from customer_management.init import load_customer_management
from opportunity_management.init import load_opportunity_management
from contract_management.init import load_contract_management
from financial_management.init import load_financial_management
from workflow_approval.init import load_workflow_approval
from unified_dashboard.init import load_unified_dashboard


def get_module_dbname(m):
    """
    Required function for all database-using modules.
    Returns the database name configured in config.json.
    Each module can use different databases.
    """
    return 'crm_db'  # Must match database name in config.json


def init():
    env = ServerEnv()
    env.get_module_dbname = get_module_dbname

    # Load modules in dependency order
    load_appbase()
    load_rbac()

    # Initialize permissions from perm_config.py
    # This ensures all UI/DSPY paths and CRUD paths are registered
    import sys
    sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
    from app.init_permissions import init_permissions_from_config
    import asyncio
    loop = asyncio.new_event_loop()
    loop.run_until_complete(init_permissions_from_config('crm_db'))
    loop.close()

    load_customer_management()
    load_opportunity_management()
    load_contract_management()
    load_financial_management()
    load_workflow_approval()
    load_unified_dashboard()


if __name__ == '__main__':
    webapp(init)
