try:
    from lchttp.json import json_loads
except ImportError:
    from json import loads as json_loads
import os.path
import socket
from http.client import HTTPConnection, HTTPResponse
from typing import Any


class HTTPUnixSocketConnection(HTTPConnection):
    def __init__(self, unix_socket: str, timeout: int | None = None, blocksize: int = 8192) -> None:
        super().__init__("localhost", timeout, blocksize)
        self.unix_socket = unix_socket

    def connect(self) -> None:
        if not os.path.exists(self.unix_socket):
            raise IOError(f"Socket {self.unix_socket} does not exist")

        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.settimeout(self.timeout)
        self.sock.connect(self.unix_socket)


class UnixSocketResponse(HTTPResponse):
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self.status_code = self.status
        self._content = ''

    def json(self) -> Any:
        return json_loads(self.read())


class LCRequestUnixSocket(HTTPUnixSocketConnection):
    response_class = UnixSocketResponse
