import re
import subprocess

# Strict allowlist for container hostnames / service aliases.
_CONTAINER_NAME_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._-]*$')


def exec_in_container(container_name, cmd, capture_output=True):
    """Send a command to a container's command dispatcher via socat TCP."""
    if not _CONTAINER_NAME_RE.match(container_name):
        raise ValueError(f"Invalid container name: {container_name!r}")

    args = [str(arg) for arg in cmd]
    for arg in args:
        if any(c in arg for c in (' ', '\t', '\n', '\r')):
            raise ValueError(
                f"Command argument must not contain whitespace: {arg!r}"
            )

    cmd_line = " ".join(args) + "\n"

    return subprocess.run(
        ["socat", "-", f"TCP:{container_name}:6969"],
        input=cmd_line,
        capture_output=capture_output,
        text=True,
    )


def send_sighup(container_name, proc_name):
    """Send SIGHUP to a named process inside a container. """
    return exec_in_container(container_name, ["sighup", proc_name])
