"""
Brynq Enterprise Integration — Glue module that wires enterprise features
into the main MCP server and web dashboard.

Connects:
  - brynq.enterprise_tools   -> server tool list + handler dict
  - brynq.dashboard_ui_enterprise -> dashboard HTML (CSS, panels, JS)
  - brynq.dashboard_enterprise    -> dashboard API routes

All imports are guarded with try/except ImportError so the system degrades
gracefully when enterprise modules are not yet installed.
"""


def register_enterprise_tools(tools_list: list, handlers_dict: dict) -> int:
    """Register enterprise MCP tools into the server's tool list and handler map.

    Args:
        tools_list: The server's TOOLS list to extend with enterprise tools.
        handlers_dict: The server's handler dict to update with enterprise handlers.

    Returns:
        The number of enterprise tools that were added (0 if module unavailable).
    """
    try:
        from brynq.enterprise_tools import ENTERPRISE_TOOLS, ENTERPRISE_HANDLERS
    except ImportError:
        return 0

    tools_list.extend(ENTERPRISE_TOOLS)
    handlers_dict.update(ENTERPRISE_HANDLERS)
    return len(ENTERPRISE_TOOLS)


def patch_dashboard_html(html: str) -> str:
    """Inject enterprise CSS, HTML panels, and JS into the dashboard HTML.

    Performs targeted string replacements against known markers in the
    base dashboard template. If the enterprise UI module is unavailable
    or a marker is missing, the original HTML is returned unmodified.

    Args:
        html: The raw DASHBOARD_HTML string from brynq.dashboard.

    Returns:
        The patched HTML with enterprise UI elements inserted.
    """
    try:
        from brynq.dashboard_ui_enterprise import (
            ENTERPRISE_CSS,
            ENTERPRISE_HTML,
            ENTERPRISE_JS,
        )
    except ImportError:
        return html

    # ── 1. Inject enterprise CSS before </style> ────────────────────────
    style_marker = "</style>"
    if style_marker in html:
        html = html.replace(
            style_marker,
            ENTERPRISE_CSS + "\n" + style_marker,
            1,
        )

    # ── 2. Inject enterprise tab buttons after the Cron tab button ──────
    cron_tab_marker = (
        """<button class="tab-btn" data-tab="cron" onclick="switchTab('cron')">"""
        """Cron <span class="tab-count" id="tabCronCount">0</span></button>"""
    )
    if cron_tab_marker in html:
        html = html.replace(
            cron_tab_marker,
            cron_tab_marker + "\n" + ENTERPRISE_HTML,
            1,
        )

    # ── 3. Inject enterprise panels before the stats-bar ────────────────
    stats_marker = '<div class="stats-bar" id="statsBar">'
    if stats_marker in html:
        html = html.replace(
            stats_marker,
            ENTERPRISE_HTML + "\n" + stats_marker,
            1,
        )

    # ── 4. Inject enterprise JS before the refreshAll() function ────────
    refresh_marker = "function refreshAll() {"
    if refresh_marker in html:
        html = html.replace(
            refresh_marker,
            ENTERPRISE_JS + "\n\n  " + refresh_marker,
            1,
        )

    # ── 5. Wire enterprise fetchers into refreshAll() ───────────────────
    #   Insert enterprise fetch calls right after the existing cron fetch
    #   line inside refreshAll() so they participate in the periodic refresh.
    cron_refresh_line = (
        "else if (currentTab === 'cron') fetchCron();"
    )
    if cron_refresh_line in html:
        enterprise_refresh_calls = (
            "else if (currentTab === 'cron') fetchCron();\n"
            "    // Enterprise tab data (lazy-loaded per active tab)\n"
            "    if (typeof fetchEnterpriseData === 'function') fetchEnterpriseData(currentTab);"
        )
        html = html.replace(cron_refresh_line, enterprise_refresh_calls, 1)

    return html


def register_enterprise_routes(handler, path: str, params) -> bool:
    """Delegate an HTTP request to enterprise route handlers if applicable.

    Args:
        handler: The DashboardHandler instance (has _send_json, etc.).
        path: The parsed URL path (e.g. "/api/enterprise/audit").
        params: The parsed query-string parameters dict.

    Returns:
        True if the enterprise module handled the route, False otherwise.
    """
    try:
        from brynq.dashboard_enterprise import (
            register_enterprise_routes as _enterprise_routes,
        )
    except ImportError:
        return False

    return _enterprise_routes(handler, path, params)
