# platform/deskclaw/adapters/registry.py
# ═══════════════════════════════════════════════════════════════
# Adapter Registry — U 盘式接入的核心基础设施
# 一行装饰器完成注册，get_adapter() 按名称实例化
# ═══════════════════════════════════════════════════════════════

from typing import Type

from deskclaw.adapters.protocol import AgentAdapter

_REGISTRY: dict[str, Type[AgentAdapter]] = {}
_INSTANCE_REGISTRY: dict[str, AgentAdapter] = {}


def register_adapter(name: str):
    """装饰器：注册 Agent Adapter 类到全局 Registry"""

    def decorator(cls: Type[AgentAdapter]):
        if name in _REGISTRY:
            raise ValueError(
                f"Adapter '{name}' already registered by {_REGISTRY[name].__name__}"
            )
        _REGISTRY[name] = cls
        return cls

    return decorator


def register_adapter_instance(name: str, instance: AgentAdapter) -> bool:
    """
    注册一个已实例化的 Adapter（用于动态加载的 HTTP 适配器）。

    Returns:
        True if newly registered, False if name already exists.
    """
    if name in _REGISTRY or name in _INSTANCE_REGISTRY:
        return False
    _INSTANCE_REGISTRY[name] = instance
    return True


def get_adapter(name: str, **config) -> AgentAdapter:
    """按名称实例化 Adapter，config 透传给 __init__"""
    if name in _INSTANCE_REGISTRY:
        return _INSTANCE_REGISTRY[name]

    if name not in _REGISTRY:
        available = ", ".join(sorted(list_adapters()))
        raise KeyError(f"Unknown adapter '{name}'. Available: [{available}]")
    return _REGISTRY[name](**config)


def list_adapters() -> list[str]:
    """列出所有已注册 Adapter 名称（包括静态注册和动态实例注册）"""
    return sorted(set(_REGISTRY.keys()) | set(_INSTANCE_REGISTRY.keys()))
