"""bridge/connectors/registry.py — Connector discovery and switching."""

from __future__ import annotations

from typing import Any

from bridge.connectors.base import ConnectorBase


class ConnectorRegistry:
    """Manages available broker connectors and the active one."""

    def __init__(self):
        self._connectors: dict[str, ConnectorBase] = {}
        self._active: str = ""

    def register(self, name: str, connector: ConnectorBase) -> None:
        self._connectors[name] = connector
        if not self._active:
            self._active = name

    def switch(self, name: str) -> bool:
        if name in self._connectors:
            self._active = name
            return True
        return False

    def get_active(self) -> ConnectorBase | None:
        return self._connectors.get(self._active)

    def list_connectors(self) -> list[dict[str, Any]]:
        return [
            {"name": name, "active": name == self._active, "connected": c.is_connected()}
            for name, c in self._connectors.items()
        ]

    def get_price(self, symbol: str = "") -> dict[str, Any]:
        c = self.get_active()
        return c.get_price(symbol) if c else {}

    def get_account(self) -> dict[str, Any]:
        c = self.get_active()
        return c.get_account() if c else {}

    def get_positions(self) -> list[dict[str, Any]]:
        c = self.get_active()
        return c.get_positions() if c else []


_registry: ConnectorRegistry | None = None


def get_registry() -> ConnectorRegistry:
    global _registry
    if _registry is None:
        _registry = ConnectorRegistry()
        from bridge.connectors.mt5_connector import MT5Connector
        _registry.register("mt5", MT5Connector())
    return _registry
