import contextlib
import tempfile
import socket
import os
import threading


def progress_socket_reader(sock, handler):
    conn, _ = sock.accept()
    with contextlib.closing(conn):
        data = b""
        while True:
            more_data = conn.recv(16)
            if not more_data:
                break
            data += more_data
            lines = data.split(b"\n")
            for line in lines[:-1]:
                line = line.decode()
                parts = line.split("=")
                key = parts[0] if len(parts) > 0 else None
                value = parts[1] if len(parts) > 1 else None
                try:
                    handler(key, value)
                except Exception as e:
                    print(f"error in handler: {e}")
            data = lines[-1]


@contextlib.contextmanager
def progress_socket(handler):
    with tempfile.TemporaryDirectory() as temp_dir:
        socket_filename = os.path.join(temp_dir, "sock")
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        with contextlib.closing(sock):
            sock.bind(socket_filename)
            sock.listen(1)
            thd = threading.Thread(
                target=progress_socket_reader,
                args=(sock, handler),
                daemon=True,
            )
            thd.start()
            yield socket_filename
