import sys
import carb.tokens
import carb.settings
import omni.ext
import omni.kit.pipapi

# Try import to allow documentation build without debugpy
try:
    import debugpy
except ModuleNotFoundError:
    pass


def _print(msg):
    print(f"[omni.kit.debug.python] {msg}")


def wait_for_client():
    _print("Waiting for debugger to connect...")
    debugpy.wait_for_client()


def breakpoint():
    wait_for_client()
    debugpy.breakpoint()


def is_attached() -> bool:
    return debugpy.is_client_connected()


def enable_logging():
    path = carb.tokens.get_tokens_interface().resolve("${logs}")
    _print(f"Enabled logging to '{path}'")
    debugpy.log_to(path)


_listen_address = None


def get_listen_address():
    return _listen_address


class Extension(omni.ext.IExt):
    def on_startup(self):
        settings = carb.settings.get_settings()

        host = settings.get("/exts/omni.kit.debug.python/host")
        port = settings.get("/exts/omni.kit.debug.python/port")
        debugpyLogging = settings.get("/exts/omni.kit.debug.python/debugpyLogging")
        waitForClient = settings.get("/exts/omni.kit.debug.python/waitForClient")
        break_ = settings.get("/exts/omni.kit.debug.python/break")

        if debugpyLogging:
            enable_logging()

        # Start debugging server
        python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
        python_cmd = sys.prefix + "/" + python_exe
        debugpy.configure(python=python_cmd)

        global _listen_address
        try:
            _listen_address = debugpy.listen((host, port))
            _print(f"Running python debugger on: {_listen_address}")
        except Exception as e:
            _print(f"Error running python debugger: {e}")

        if waitForClient:
            wait_for_client()

        if break_:
            breakpoint()
