"""
Utility functions for turning simple mode names into real local IP addresses.
This helps other tools safely connect only to the local machine, never to
external hosts. The resolver supports common options like IPv4 loopback,
IPv6 loopback, and the system’s primary IPv4 address.

The primary IPv4 lookup uses a harmless trick: it “connects” to 8.8.8.8 without
sending any data, letting the OS tell us which local interface would be used.
If anything goes wrong, the function simply returns None.

These helpers keep networking code simple, predictable, and safe for interns
and higher‑level probes that rely on local‑only behavior.
"""


import socket


def resolve_local_address(local_address_mode):
    """resolve a local address mode, into an address that is local to the current machine"""
    if local_address_mode == "ipv4_loopback":
        return "127.0.0.1"
    if local_address_mode == "ipv6_loopback":
        return "::1"
    if local_address_mode == "hostname_localhost":
        return "localhost"
    if local_address_mode == "primary_ipv4":
        return get_primary_ipv4()

    
def get_primary_ipv4() -> str | None:
    """
    Returns the primary IPv4 address of the machine.
    Returns None if it cannot be determined.
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # No packets are sent; this just triggers routing selection.
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]
    except Exception:
        return
    finally:
        s.close()


if __name__ == "__main__":
    print("IPv4 Loopback:", resolve_local_address("ipv4_loopback"))
    print("IPv6 Loopback:", resolve_local_address("ipv6_loopback"))
    print("Hostname Localhost:", resolve_local_address("hostname_localhost"))
    print("Primary IPv4:", resolve_local_address("primary_ipv4"))