from __future__ import annotations

import ipaddress
import re
from typing import List, Tuple


def is_public_ip(ip_text: str) -> bool:
    """判断字符串是否为公网 IP，排除内网、回环、链路本地等地址。"""
    try:
        ip_obj = ipaddress.ip_address(ip_text)
    except ValueError:
        return False
    return not (
        ip_obj.is_private
        or ip_obj.is_loopback
        or ip_obj.is_link_local
        or ip_obj.is_multicast
        or ip_obj.is_reserved
        or ip_obj.is_unspecified
    )


def extract_public_ips(text: str) -> List[str]:
    """从文本里提取不重复的公网 IPv4 地址。"""
    seen = set()
    ips: List[str] = []
    for match in re.finditer(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text or ""):
        ip_text = match.group(0)
        if is_public_ip(ip_text) and ip_text not in seen:
            seen.add(ip_text)
            ips.append(ip_text)
    return ips


def sort_ipv4(value: str) -> Tuple[int, int, int, int]:
    """把 IPv4 字符串转换成可排序的四段整数元组。"""
    try:
        parts = [int(part) for part in str(value).split(".")]
        if len(parts) == 4:
            return parts[0], parts[1], parts[2], parts[3]
    except Exception:
        pass
    return 0, 0, 0, 0
