"""Lifecycle owner for the OpenClaw embedding worker."""

from __future__ import annotations

import threading


_worker_thread = None
_worker_lock = threading.Lock()


def _run_worker() -> None:
    from services.openclaw_learning_service import run_embedding_worker_loop

    run_embedding_worker_loop()


def start_embedding_worker() -> threading.Thread:
    """Start exactly one worker in the dedicated scheduler process."""
    global _worker_thread

    with _worker_lock:
        if _worker_thread is not None and _worker_thread.is_alive():
            return _worker_thread
        worker = threading.Thread(
            target=_run_worker,
            daemon=True,
            name="openclaw-embedding-worker",
        )
        worker.start()
        _worker_thread = worker
        return worker


def embedding_worker_runtime_status() -> dict:
    worker = _worker_thread
    return {
        "runtime_owner": "momo-scheduler",
        "thread_name": worker.name if worker else None,
        "running": bool(worker and worker.is_alive()),
    }


__all__ = ["embedding_worker_runtime_status", "start_embedding_worker"]
