"""
Runtime compatibility patch for locked-down Windows environments.

`livekit-agents` unconditionally imports its `tokenize.blingfire` module, which in turn
imports a native extension (`lk_blingfire`). On some systems this extension is blocked by
Windows Application Control / WDAC, causing the entire `livekit.agents` import to fail.

We don't rely on blingfire for the MCube WS bridge, so we safely replace
`livekit.agents.tokenize.blingfire` with the pure-Python tokenizer implementation.

Python automatically imports `sitecustomize` on startup (unless `-S` is used), as long as
this file is on `sys.path` (it is when running from `backend/agent_runtime`).
"""

from __future__ import annotations

import sys
import types


def _install_livekit_blingfire_stub() -> None:
    module_name = "livekit.agents.tokenize.blingfire"

    # If something already provided it, don't interfere.
    if module_name in sys.modules:
        return

    try:
        # Import the basic tokenizer implementation from livekit-agents.
        # This import path avoids the native blingfire extension.
        from livekit.agents.tokenize import basic as _basic  # type: ignore
    except Exception:
        # If livekit-agents itself isn't installed, nothing to do.
        return

    stub = types.ModuleType(module_name)
    stub.__dict__.update(
        {
            "__all__": ["SentenceTokenizer"],
            "SentenceTokenizer": _basic.SentenceTokenizer,
        }
    )

    sys.modules[module_name] = stub


_install_livekit_blingfire_stub()

