from __future__ import annotations

from .numeric import safe_int

PROTO_NAME_MAP = {
    1: "ICMP", 6: "TCP", 17: "UDP", 47: "GRE", 50: "ESP", 51: "AH", 58: "ICMPv6", 132: "SCTP",
}
PROTO_ALIASES = {
    "TCP": "TCP", "UDP": "UDP", "ICMP": "ICMP", "ICMPV6": "ICMPv6", "ICMP6": "ICMPv6",
    "GRE": "GRE", "ESP": "ESP", "AH": "AH", "SCTP": "SCTP",
}

def normalize_protocol(value) -> str:
    """Normalize protocol number/name into a canonical uppercase string."""
    v_int = safe_int(value, None)
    if v_int is not None:
        return PROTO_NAME_MAP.get(v_int, str(v_int))
    s = str(value).strip().upper()
    if s.isdigit():
        return PROTO_NAME_MAP.get(int(s), s)
    return PROTO_ALIASES.get(s, s)


def protocol_context(proto: str):
    """Return contextual flags and grammatical elements for a given protocol."""
    p = (proto or "").upper()
    is_tcp = p == "TCP"
    is_udp = p == "UDP"
    is_sctp = p == "SCTP"
    is_icmp = p in {"ICMP", "ICMPV6"}
    has_ports = is_tcp or is_udp or is_sctp
    if is_tcp:
        noun, article = "connection", "A"
    elif is_udp or is_sctp:
        noun, article = "communication", "A"
    elif is_icmp:
        noun, article = "exchange", "An"
    else:
        noun, article = "flow", "A"
    return {
        "is_tcp": is_tcp,
        "has_ports": has_ports,
        "noun": noun,
        "article": article,
        "has_tcp_flags": is_tcp,
        "has_tcp_handshake": is_tcp,
    }
