import socket
import json

# Initialize the socket without connecting
watcher_sock = None

class Watcher:
    @staticmethod
    def ensure_socket_connected():
        global watcher_sock
        if watcher_sock is None or watcher_sock.fileno() == -1:  # Checks if socket is not initialized or closed
            try:
                # Attempt to initialize and connect the socket
                watcher_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                watcher_sock.connect("/tmp/oscar_watcher.sock")
            except socket.error:
                # If connection fails, set sock to None and do nothing
                watcher_sock = None

    @staticmethod
    def log_watch(var_name, message):
        global watcher_sock
        Watcher.ensure_socket_connected()  # Ensure the socket is connected before attempting to log
        if watcher_sock:  # Proceed only if sock is not None (i.e., is connected)
            message_json = json.dumps([var_name, message])
            try:
                watcher_sock.sendall(message_json.encode('utf-8') + b'\n')
            except socket.error:
                # Handle potential error in sending (e.g., if connection was lost)
                watcher_sock = None  # Ensure that the next attempt will try to reconnect
            finally:
                watcher_sock.close()  # Close the current socket to clean up resources
                watcher_sock = None  # Reset sock to ensure reconnection attempt on next call
