""" service/__init__.py """

import threading
import time

import requests

WORDS_SVC_URL = "http://127.0.0.1:3888"


class ServiceReady:
    """Class to monitor and track the readiness of the words service."""

    ready = False
    started = False

    def __init__(self):
        self.url = f"{WORDS_SVC_URL}/health"
        if not self.started:
            self.started = True
            self.start_monitor()

    def start_monitor(self):
        """
        Start a background thread to monitor the health endpoint.
        """

        def monitor():
            while not ServiceReady.ready:
                try:
                    # Check the health endpoint
                    response = requests.get(self.url, timeout=2)
                    if response.status_code == 200:
                        ServiceReady.ready = True
                except requests.RequestException:
                    time.sleep(2)

        # Start the thread
        thread = threading.Thread(target=monitor, daemon=True)
        thread.start()


ready = ServiceReady().ready
