from __future__ import annotations

import inspect
import warnings
from typing import Any

from flownet.proactive.registry import ServiceRegistry


SERVICE_MANAGER_ACTOR_ID = "__services__"
CONTAINER_EVENT_SERVICE_NAME = "container_event_stream"


class ServiceManagerActor:
    def __init__(
        self,
        registry: ServiceRegistry | None = None,
        node_control: Any | None = None,
    ):
        if registry is None and node_control is None:
            raise ValueError("ServiceManagerActor requires registry or node_control delegate.")
        self._registry = registry
        self._node_control = node_control

    def _warn_deprecated(self, method: str) -> None:
        warnings.warn(
            f"`{SERVICE_MANAGER_ACTOR_ID}.{method}` is deprecated. "
            "Use node control APIs instead.",
            DeprecationWarning,
            stacklevel=3,
        )

    def list_services(self) -> list[dict[str, Any]]:
        if self._node_control is not None:
            self._warn_deprecated("list_services")
            return self._node_control.invoke("list_services")
        return self._registry.list_services()

    async def subscribe_flow(
        self,
        service_name: str,
        flow_task: Any,
        execution_address: str,
        tags: dict[str, str] | None = None,
    ) -> str:
        if self._node_control is not None:
            self._warn_deprecated("subscribe_flow")
            result = self._node_control.invoke(
                "subscribe_service_flow",
                service_name,
                flow_task,
                execution_address,
                tags=tags,
            )
            if inspect.isawaitable(result):
                return await result
            return result
        return self._registry.subscribe_flow(service_name, flow_task, execution_address, tags)

    async def unsubscribe_flow(self, subscription_id: str) -> bool:
        if self._node_control is not None:
            self._warn_deprecated("unsubscribe_flow")
            result = self._node_control.invoke("unsubscribe_service_flow", subscription_id)
            if inspect.isawaitable(result):
                return bool(await result)
            return bool(result)
        return self._registry.unsubscribe_flow(subscription_id)


__all__ = [
    "SERVICE_MANAGER_ACTOR_ID",
    "CONTAINER_EVENT_SERVICE_NAME",
    "ServiceManagerActor",
]
