"""Cross-post validator: checks one post against the documented limits of each social network.

Free to use (MIT). Published by APIWings: https://apiwings.com/blog/post-to-multiple-social-networks-api
Limits checked against each network's official documentation on 2026-11-23.
Requires: pip install regex   (for grapheme clusters and emoji detection)
"""
import unicodedata
import regex

EMOJI = regex.compile(r"\p{Extended_Pictographic}")
URL_RE = regex.compile(r"https?://\S+", regex.IGNORECASE)
X_LIGHT = [(0x0000, 0x10FF), (0x2000, 0x200D), (0x2010, 0x201F), (0x2032, 0x2037)]


def graphemes(s: str):
    return regex.findall(r"\X", s)


def count_x(text: str) -> int:
    """X: NFC, twitter-text v3 ranges weigh 1, everything else 2, URLs 23, emoji 2."""
    s = unicodedata.normalize("NFC", text)
    n = 23 * len(URL_RE.findall(s))
    s = URL_RE.sub("", s)
    for g in graphemes(s):
        if EMOJI.search(g):
            n += 2
            continue
        for ch in g:
            cp = ord(ch)
            n += 1 if any(a <= cp <= b for a, b in X_LIGHT) else 2
    return n


def count_graphemes(s: str) -> int:
    return len(graphemes(s))


def count_utf16(s: str) -> int:
    return len(s.encode("utf-16-le")) // 2


def count_bytes(s: str) -> int:
    return len(s.encode("utf-8"))


def count_threads(s: str) -> int:
    """Threads: emojis count as their UTF-8 byte length."""
    return sum(count_bytes(g) if EMOJI.search(g) else len(g) for g in graphemes(s))


LIMITS = {
    "x": {"text": (280, count_x, "weighted characters"), "max_images": 4},
    "bluesky": {"text": (300, count_graphemes, "graphemes"), "max_images": 4, "max_image_bytes": 1_000_000},
    "threads": {"text": (500, count_threads, "characters"), "max_images": 20, "image_formats": ["jpeg", "png"], "max_image_bytes": 8_388_608},
    "instagram": {"text": (2200, len, "characters"), "max_images": 20, "image_formats": ["jpeg"], "media_required": True, "max_hashtags": 30, "max_mentions": 20},
    "tiktok_photo": {"title": (90, count_utf16, "UTF-16 units"), "text": (4000, count_utf16, "UTF-16 units"), "max_images": 35, "media_required": True},
    "youtube": {"title": (100, len, "characters"), "text": (5000, count_bytes, "bytes"), "video_only": True},
    "linkedin": {},
    "facebook_page": {},
}


def validate(post: dict, networks=None) -> dict:
    """post = {"text": str, "title": str?, "images": [{"format": "jpeg", "bytes": int}], "video": bool}
    Returns {network: [issues]}; an empty list means no documented limit is broken."""
    out, images = {}, post.get("images", [])
    for net in networks or LIMITS:
        L, issues = LIMITS.get(net), []
        if L is None:
            out[net] = ["unknown network"]
            continue
        if "text" in L:
            mx, fn, unit = L["text"]
            n = fn(post.get("text", ""))
            if n > mx:
                issues.append(f"text is {n} {unit}, max {mx}")
        if "title" in L:
            mx, fn, unit = L["title"]
            t = post.get("title", "")
            if not t and net == "youtube":
                issues.append("title is required")
            if fn(t) > mx:
                issues.append(f"title is {fn(t)} {unit}, max {mx}")
        if L.get("video_only") and not post.get("video"):
            issues.append("publishes video only")
        if L.get("media_required") and not images and not post.get("video"):
            issues.append("needs an image or video")
        if "max_images" in L and len(images) > L["max_images"]:
            issues.append(f"{len(images)} images, max {L['max_images']}")
        if "image_formats" in L and any(i.get("format", "").lower() not in L["image_formats"] for i in images):
            issues.append(f"image format must be {' or '.join(L['image_formats'])}")
        if "max_image_bytes" in L:
            big = [i for i in images if i.get("bytes", 0) > L["max_image_bytes"]]
            if big:
                issues.append(f"{len(big)} image(s) over {L['max_image_bytes']} bytes")
        if "max_hashtags" in L and len(regex.findall(r"(?:^|\s)#\w+", post.get("text", ""))) > L["max_hashtags"]:
            issues.append(f"more than {L['max_hashtags']} hashtags")
        if "max_mentions" in L and len(regex.findall(r"(?:^|\s)@\w+", post.get("text", ""))) > L["max_mentions"]:
            issues.append(f"more than {L['max_mentions']} @ mentions")
        out[net] = issues
    return out


if __name__ == "__main__":
    example = {"text": "x" * 370 + " https://apiwings.com/blog", "images": [{"format": "jpeg", "bytes": 500_000}] * 5}
    for net, issues in validate(example).items():
        print(f"{net:14} {'OK' if not issues else '; '.join(issues)}")
