# DOCS_REF:
# - docs/user/04-services-sources-topics.md
# - docs/user/cookbook/topic-to-flow-to-topic.md
# - docs/user/reference/api-surface.md
# DOCS_SYNC:
# - If service/source lifecycle APIs change, update the referenced docs and
#   examples/docs/{services_sources_topics_example.py,cookbook_topic_flow_topic_example.py}.

from __future__ import annotations

from typing import Any

from flownet.runtime.runtime import get_runtime, try_get_runtime
from flownet.runtime.kernel import RuntimeKernel, get_runtime_kernel, try_get_runtime_kernel


def get_services() -> RuntimeKernel:
    get_runtime()
    return get_runtime_kernel()


def try_get_services() -> RuntimeKernel | None:
    runtime = try_get_runtime()
    if runtime is None:
        return None
    return try_get_runtime_kernel()


def start_service(name: str, service_spec: Any, *args, **kwargs):
    return get_services().start_service(name, service_spec, *args, **kwargs)


def publish_service(name: str, service_spec: Any, *args, **kwargs):
    return start_service(name, service_spec, *args, **kwargs)


def stop_service(name: str) -> bool:
    return get_services().stop_service(name)


def list_services() -> list[dict[str, Any]]:
    return get_services().list_services()


def start_source(source_id: str, source_spec: Any, *args, **kwargs):
    return get_services().start_source(source_id, source_spec, *args, **kwargs)


def publish_topic(topic_id: str, source_spec: Any, *args, **kwargs):
    return start_source(topic_id, source_spec, *args, **kwargs)


def stop_source(source_id: str) -> bool:
    return get_services().stop_source(source_id)


def list_sources() -> list[dict[str, Any]]:
    return get_services().list_sources()


def local_address() -> str:
    return get_services().local_address()


__all__ = [
    "get_services",
    "try_get_services",
    "start_service",
    "publish_service",
    "stop_service",
    "list_services",
    "start_source",
    "publish_topic",
    "stop_source",
    "list_sources",
    "local_address",
]
