"""InsAIts CLI entry points — fast startup, no heavy SDK imports.

These functions are used as console_scripts entry points by setuptools.
They locate and load the server modules directly via importlib, bypassing
the heavy insa_its/__init__.py chain (torch/sentence-transformers ~44s).
"""
import importlib.util
import os
import sys


def _find_module(subpath):
    """Locate a file inside the insa_its package without importing it."""
    spec = importlib.util.find_spec("insa_its")
    if spec and spec.submodule_search_locations:
        for loc in spec.submodule_search_locations:
            candidate = os.path.join(loc, *subpath.split("/"))
            if os.path.exists(candidate):
                return candidate
    return None


def _run_module(subpath, name):
    """Load and execute a module's main() function."""
    path = _find_module(subpath)
    if not path:
        print(f"Error: {name} not found. Is insa-its installed?", file=sys.stderr)
        sys.exit(1)
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    mod.main()


def collector():
    """Entry point for ``insaits-collector`` command."""
    _run_module("collector/server.py", "insaits_collector")


def dashboard():
    """Entry point for ``insaits-dashboard`` command."""
    _run_module("web/server.py", "insaits_dashboard")
