from __future__ import annotations


def normalize_flags(flags_str):
    if not isinstance(flags_str, str) or not flags_str.strip():
        return [], set()
    parts = [p.strip().upper() for p in flags_str.split(",") if p.strip()]
    order = ["CWR", "ECE", "URG", "SYN", "ACK", "PSH", "FIN", "RST"]
    uniq, seen = [], set()
    for p in parts:
        if p and p not in seen:
            uniq.append(p)
            seen.add(p)
    uniq_sorted = sorted(uniq, key=lambda f: order.index(f) if f in order else 999)
    return uniq_sorted, set(uniq)


def tcp_flags_story(flags_str) -> str:
    """Generate a narrative for TCP flag combinations."""
    if flags_str is None:
        return "TCP flags unavailable"
    ordered, s = normalize_flags(flags_str)
    if not s:
        return "without clear TCP signals"

    phrases = []
    if "ECE" in s or "CWR" in s:
        phrases.append("indicating congestion control (ECE/CWR)")
    if "SYN" in s and "ACK" in s:
        phrases.append("acknowledging the connection setup (SYN/ACK)")
    elif "SYN" in s:
        phrases.append("attempting to start the connection (SYN)")
    if "FIN" in s and "ACK" in s:
        phrases.append("closing the connection gracefully (FIN/ACK)")
    elif "RST" in s:
        phrases.append("resetting the connection abruptly (RST)")
    if "PSH" in s:
        phrases.append("pushing application data (PSH)")
    if "URG" in s:
        phrases.append("marking urgent data (URG)")
    if "ACK" in s and len(phrases) == 0:
        phrases.append("acknowledging packets (ACK)")

    if not phrases:
        return f"with an unusual TCP flag pattern ({'/'.join(ordered)})"

    return ", then ".join(phrases)


def handshake_story(state) -> str:
    """Generate a human-readable handshake summary."""
    if not isinstance(state, str) or not state.strip():
        return "had an unknown handshake status"

    s = state.strip().lower()

    if s == "handshake completed":
        return "the handshake was successfully completed"

    if s == "handshake partial":
        return "the handshake was only partially completed"

    if s == "no handshake":
        return "no handshake took place"

    if s == "error":
        return "the handshake failed with errors"

    return f"the handshake status was '{state}'"
