"""PATCH casa 2026-12-04: I/O robusto p/ pyiotdevice.

- 1 conexão por vez por IP (o módulo Wi-Fi tem poucos sockets)
- lê até EOF/Content-Length (não só um read(1024))
- SEMPRE fecha o socket (a lib original vazava em timeout/erro)
"""
from __future__ import annotations

import asyncio
import contextlib
import logging

import pyiotdevice.get_thing_info as _gti
import pyiotdevice.send_ac_command as _sac
import pyiotdevice.socket_utils as _su
from pyiotdevice.custom_exceptions import InvalidDataException

_LOGGER = logging.getLogger(__name__)
_LOCKS: dict[str, asyncio.Lock] = {}


def _lock(ip: str) -> asyncio.Lock:
    if ip not in _LOCKS:
        _LOCKS[ip] = asyncio.Lock()
    return _LOCKS[ip]


async def _read_all(reader: asyncio.StreamReader, timeout: float) -> bytes:
    loop = asyncio.get_running_loop()
    deadline = loop.time() + timeout
    data = b""
    while True:
        remaining = deadline - loop.time()
        if remaining <= 0:
            break
        chunk = await asyncio.wait_for(reader.read(4096), remaining)
        if not chunk:
            break
        data += chunk
        head, sep, body = data.partition(b"\r\n\r\n")
        if sep:
            for line in head.split(b"\r\n"):
                k, _, v = line.strip().partition(b":")
                if k.lower() == b"content-length":
                    with contextlib.suppress(ValueError):
                        if len(body) >= int(v.strip()):
                            return data
    return data


async def async_send_http_request(
    ip_address: str, port: int = _su.DEFAULT_PORT, request_str: str = "", timeout: int = 10
):
    async with _lock(ip_address):
        reader, writer = await asyncio.wait_for(
            asyncio.open_connection(ip_address, port), min(timeout, 6)
        )
        try:
            writer.write(request_str.encode("utf-8"))
            await writer.drain()
            raw = await _read_all(reader, timeout)
        finally:
            writer.close()
            with contextlib.suppress(Exception):
                await asyncio.wait_for(writer.wait_closed(), 2)
        await asyncio.sleep(0.2)  # folga p/ o módulo liberar o socket
    text = raw.decode("utf-8", errors="replace")
    if "404 Not Found" in text:
        raise InvalidDataException()
    parts = text.split("\r\n\r\n")
    if len(parts) < 2 or not parts[1]:
        _LOGGER.debug("Resposta inválida de %s (%d bytes): %r", ip_address, len(raw), raw[:200])
        raise InvalidDataException()
    return parts[0], parts[1]


def install() -> None:
    _su.async_send_http_request = async_send_http_request
    _gti.async_send_http_request = async_send_http_request
    _sac.async_send_http_request = async_send_http_request
