"""Unified Registry — single owner of tools and skills.

Composes ``ToolRegistry`` and ``SkillRegistry`` into one object owned
at bootstrap.  The existing ``get_tool_registry()`` and
``get_skill_registry()`` functions delegate here so all existing
consumers work without changes.

Usage::

    from core.registry import get_registry, set_registry

    reg = get_registry()
    reg.tools.get("web.search")
    reg.skills.get("research")
"""

import threading

from core.skills.registry import SkillRegistry
from core.tools.registry import ToolRegistry


class Registry:
    """Unified registry — owns both tools and skills.

    Created once at bootstrap and installed as the module-level global.
    The old ``get_tool_registry()`` / ``get_skill_registry()`` functions
    read from this object so all existing call-sites keep working.
    """

    def __init__(
        self,
        *,
        tools: ToolRegistry | None = None,
        skills: SkillRegistry | None = None,
    ) -> None:
        self.tools = tools or ToolRegistry()
        self.skills = skills or SkillRegistry()


# ---------------------------------------------------------------------------
# Module-level singleton
# ---------------------------------------------------------------------------

_registry: Registry | None = None
_lock = threading.Lock()


def get_registry() -> Registry:
    """Get the global unified registry.

    Lazily created if ``set_registry()`` hasn't been called yet.
    """
    global _registry
    if _registry is None:
        with _lock:
            if _registry is None:
                _registry = Registry()
    return _registry


def set_registry(registry: Registry) -> None:
    """Install *registry* as the global registry.

    Called at bootstrap to own the instance.
    Also installs the inner ``ToolRegistry`` / ``SkillRegistry`` into
    their legacy global accessors for backward compatibility.
    """
    global _registry
    _registry = registry

    # Keep legacy global accessors in sync
    from core.skills.registry import set_skill_registry
    from core.tools.registry import set_tool_registry

    set_tool_registry(registry.tools)
    set_skill_registry(registry.skills)


__all__ = [
    "Registry",
    "get_registry",
    "set_registry",
]
