# DOCS_REF:
# - docs/user/02-quickstart-distributed.md
# - docs/user/08-node-and-container-ops.md
# - docs/user/reference/api-surface.md
# DOCS_SYNC:
# - If daemon/container management APIs change, update distributed quickstart
#   and ops docs plus examples/docs/quickstart_distributed_example.py.

from __future__ import annotations

from flownet.api.actor_ref import ContainerRef
import flownet.api.node_control as node_control_api
from flownet.config import RuntimeConfigInput
from flownet.proactive.manager_actor import SERVICE_MANAGER_ACTOR_ID


DEFAULT_DAEMON_ADDRESS = "127.0.0.1:8787"
DEFAULT_SERVICE_MANAGER_ACTOR_ID = SERVICE_MANAGER_ACTOR_ID


def spawn_container(config: RuntimeConfigInput) -> ContainerRef:
    return spawn_container_on(DEFAULT_DAEMON_ADDRESS, config)


def spawn_container_on(daemon_address: str, config: RuntimeConfigInput) -> ContainerRef:
    return node_control_api.spawn_container_on(daemon_address, config)


def list_containers(daemon_address: str = DEFAULT_DAEMON_ADDRESS) -> list[dict[str, object]]:
    return list_containers_on(daemon_address)


def list_containers_on(daemon_address: str) -> list[dict[str, object]]:
    return node_control_api.list_containers_on(daemon_address)


def kill_container(address: str, daemon_address: str = DEFAULT_DAEMON_ADDRESS) -> bool:
    return kill_container_on(daemon_address, address)


def kill_container_on(daemon_address: str, address: str) -> bool:
    return node_control_api.kill_container_on(daemon_address, address)


def list_services(node_address: str = DEFAULT_DAEMON_ADDRESS) -> list[dict[str, object]]:
    return list_services_on(node_address)


def list_services_on(node_address: str) -> list[dict[str, object]]:
    return node_control_api.list_services_on(node_address)


def connect_to_container(address: str) -> ContainerRef:
    container_ref = ContainerRef(address=address)
    try:
        container_ref.ping().result()
    except Exception as e:
        raise ConnectionError(
            f"[FlownetRuntime] Failed to connect to container at {address}: {e}"
        ) from e
    return container_ref


__all__ = [
    "DEFAULT_DAEMON_ADDRESS",
    "DEFAULT_SERVICE_MANAGER_ACTOR_ID",
    "spawn_container",
    "spawn_container_on",
    "list_containers",
    "list_containers_on",
    "kill_container",
    "kill_container_on",
    "list_services",
    "list_services_on",
    "connect_to_container",
]
