"""Socket address helpers for Cthulhu Remote."""

import urllib.parse

from .protocol import SERVER_PORT


def address_to_host_port(address: str) -> tuple[str, int]:
    """Convert host[:port] text to a host, port tuple."""

    parsedAddress = urllib.parse.urlparse("//" + address)
    return parsedAddress.hostname or "", parsedAddress.port or SERVER_PORT


def host_port_to_address(hostPort: tuple[str, int]) -> str:
    """Convert a host, port tuple to compact host[:port] text."""

    host, port = hostPort
    if ":" in host:
        host = f"[{host}]"
    if port != SERVER_PORT:
        return f"{host}:{port}"
    return host
