from __future__ import absolute_import, print_function, unicode_literals

import importlib.util
import os
import sys


_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_MODULE_NAME = "AbletonMCP_AI_runtime"
_RUNTIME_CANDIDATES = [
    os.path.join(os.path.dirname(_SCRIPT_DIR), "abletonmcp_init.py"),  # Prioridad: runtime canonico
    os.path.join(_SCRIPT_DIR, "AbletonMCP_AI_BAK_20260328_200801", "Remote_Script.py"),  # Fallback: backup
]


def _resolve_runtime_file():
    for candidate in _RUNTIME_CANDIDATES:
        if os.path.exists(candidate):
            return candidate
    raise ImportError("Remote script runtime not found in any known location")


def _load_runtime_module():
    if _MODULE_NAME in sys.modules:
        return sys.modules[_MODULE_NAME]

    runtime_file = _resolve_runtime_file()

    spec = importlib.util.spec_from_file_location(_MODULE_NAME, runtime_file)
    if spec is None or spec.loader is None:
        raise ImportError("Unable to create module spec for %s" % runtime_file)

    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    sys.modules[_MODULE_NAME] = module
    return module


def create_instance(c_instance):
    runtime = _load_runtime_module()
    if not hasattr(runtime, "create_instance"):
        raise ImportError("Runtime module does not expose create_instance")
    return runtime.create_instance(c_instance)
