# <!-- fml-managed-agent-surface:v1 -->
"""Interpreter-local, fail-open activation for the native mini CLI only.

Imported by the owned .pth on Python startup. Ordinary Python invocations do
not import mini, read its configuration, or install an import hook. Native mini
still resolves all configuration itself on every invocation.
"""

import sys


def _explicit_override(arguments):
    values = {"--model", "--model-class", "--environment-class",
              "--task", "--cost-limit", "--output"}
    skip = False
    for argument in arguments:
        if skip:
            skip = False
            continue
        if argument == "--":
            break
        if (argument in ("--config", "--agent-class")
                or argument.startswith(("--config=", "--agent-class="))):
            return True
        skip = argument in values
        if argument.startswith("-") and not argument.startswith("--"):
            # Native mini has one short flag (-y); -c/-m/-t/-l/-o take values.
            # Click consumes the rest of a cluster, or the next argv, as a value.
            for index, option in enumerate(argument[1:], 2):
                if option == "c":
                    return True
                if option in "mtlo":
                    skip = index == len(argument)
                    break
                if option != "y":
                    break  # Unknown short options stop native parsing too.


def _native_cli():
    original = getattr(sys, "orig_argv", ())
    if sys.argv and sys.argv[0] == "-m" and "-m" in original:
        index = original.index("-m")
        return index + 1 < len(original) and original[index + 1] in (
            "minisweagent", "minisweagent.__main__", "minisweagent.run.mini",
        )
    # Console scripts have their real script path in argv at site startup.
    # Check the entrypoint rather than activating arbitrary programs named mini.
    filename = sys.argv[0] if sys.argv else ""
    if filename.replace("\\", "/").rsplit("/", 1)[-1] not in (
        "mini", "mini.exe", "mini-script.py",
        "mini-swe-agent", "mini-swe-agent.exe", "mini-swe-agent-script.py",
    ):
        return False
    try:
        if filename.lower().endswith(".exe"):
            # Windows pip launchers append a ZIP containing the same entrypoint.
            import zipfile
            with zipfile.ZipFile(filename) as script:
                return b"from minisweagent.run.mini import app" in script.read("__main__.py")
        with open(filename, "rb") as script:
            return b"from minisweagent.run.mini import app" in script.read(8192)
    except Exception:
        return False


def _patch_agents(module):
    native = module.get_agent

    def get_agent(model, env, config, *, default_type=""):
        adapted = config
        try:
            from minisweagent.agents.default import DefaultAgent
            from minisweagent.agents.interactive import InteractiveAgent
            from minisweagent.environments.local import LocalEnvironment
            # Class identity, not inheritance: custom agents/environments remain native.
            if type(env) is LocalEnvironment:
                selected = module.get_agent_class(config.get("agent_class", default_type))
                if selected is DefaultAgent or selected is InteractiveAgent:
                    from fml_mini_agent import FmlDefaultAgent, FmlInteractiveAgent
                    adapted = dict(config)
                    adapted["agent_class"] = (
                        "fml_mini_agent.FmlDefaultAgent" if selected is DefaultAgent
                        else "fml_mini_agent.FmlInteractiveAgent"
                    )
        except Exception:
            # An incompatible/missing adapter must not disable the native CLI.
            adapted = config
        return native(model, env, adapted, default_type=default_type)

    module.get_agent = get_agent


def _activate(expected_prefix):
    if not _native_cli() or _explicit_override(sys.argv[1:]):
        return
    # Other interpreters can inherit this .pth via system site-packages. Their
    # executables may resolve to the same binary, but their prefixes are distinct.
    import os
    actual_prefix = os.path.normcase(os.path.realpath(sys.prefix))
    selected_prefix = os.path.normcase(os.path.realpath(expected_prefix))
    if actual_prefix != selected_prefix:
        return
    # All mini/config imports remain lazy; ordinary Python never reaches here.
    from importlib.machinery import PathFinder

    class Loader:
        def __init__(self, native):
            self.native = native

        def __getattr__(self, name):
            return getattr(self.native, name)

        def create_module(self, spec):
            return self.native.create_module(spec)

        def exec_module(self, module):
            self.native.exec_module(module)
            try:
                _patch_agents(module)
            except Exception:
                pass

    class Finder:
        def find_spec(self, fullname, path=None, target=None):
            if fullname != "minisweagent.agents":
                return None
            spec = PathFinder.find_spec(fullname, path, target)
            if spec is not None and spec.loader is not None:
                spec.loader = Loader(spec.loader)
                sys.meta_path.remove(self)
            return spec

    sys.meta_path.insert(0, Finder())


def activate(expected_prefix):
    try:
        _activate(expected_prefix)
    except Exception:
        # .pth startup must remain usable even after a partial upgrade/uninstall.
        pass
