#!/usr/bin/env python3
"""Check alt texts against published platform limits.
Usage: python3 alt-length-check.py alt.txt   (one alt text per line, UTF-8; blank lines are skipped)
Counts each line in UTF-16 units (what the Koldflux Word counter and Bluesky count) and in code points
(Python len()). A limit is flagged against the larger count, so emoji never push you over by surprise.
The first number on each row is the line number in the file.
The first sentence ends at the first . ! ? … or 。 followed by a space or the end of the line (a closing quote
or bracket may come between). It does not stop after the abbreviations listed below (Dr., St., etc.),
a single capital initial (J.) or a word with a dot inside (U.S., a.m., e.g., koldflux.com). It is a rough split: an abbreviation
missing from the list (Blvd.) ends the sentence early, and an opener that really ends in a skipped form
(etc., U.S., a web address) runs on into the next sentence, so glance at every line, not only the flagged ones.
Exit 0 = every line fits every limit and has a first sentence under 120 characters,
1 = at least one line needs a fix, 2 = file problem or no file given."""
import sys

# Limits as published on December 1, 2026. App = the post form, API = the developer field only.
LIMITS = [
    ("Pinterest", 500),
    ("X", 1000),
    ("Threads API / Instagram API", 1000),
    ("Mastodon before 4.6", 1500),
    ("Bluesky", 2000),
    ("LinkedIn API", 4086),
]
# LinkedIn's Images API recommends keeping the whole alt text "less than 120 characters". Applying that
# number to the first sentence is our pick, not a platform rule. A first sentence of 120 or more is flagged.
FIRST_SENTENCE_TIP = 120
ABBREVIATIONS = {"dr", "mr", "mrs", "ms", "st", "prof", "jr", "sr", "vs", "no", "approx", "etc", "mt", "ave",
                 "inc", "ltd", "fig", "vol"}
OPENERS = "\"'“‘("
CLOSERS = "\"'”’)]"

def utf16(s):
    return len(s.encode("utf-16-le")) // 2

def first_sentence(s):
    for i, ch in enumerate(s):
        if ch not in ".!?…。":
            continue
        j = i + 1
        while j < len(s) and s[j] in CLOSERS:
            j += 1
        if ch != "。" and j < len(s) and s[j] != " ":
            continue
        if ch == ".":
            word = s[:i].split(" ")[-1].lstrip(OPENERS)
            # Dr. / J. / U.S. / a.m. / e.g.: a known short form, a single capital or a dot inside the word
            if word.lower() in ABBREVIATIONS or (len(word) == 1 and word.isupper()) or "." in word.strip("."):
                continue
        return s[:j]
    return s

def main(path):
    try:
        raw = open(path, "rb").read()
    except OSError as e:
        print(f"ERROR: cannot read {path}: {e.strerror}")
        return 2
    try:
        text = raw.decode("utf-8-sig")
    except UnicodeDecodeError as e:
        print(f"ERROR: {path} is not UTF-8 (byte {e.start}); save it as UTF-8 and run again")
        return 2
    rows = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
    lines = [(n, l) for n, l in enumerate(rows, 1) if l.strip()]
    if not lines:
        print(f"ERROR: {path} has no alt text lines")
        return 2
    bad = 0
    for n, line in lines:
        u, c = utf16(line), len(line)
        over = [name for name, lim in LIMITS if max(u, c) > lim]
        fs = utf16(first_sentence(line))
        notes = []
        if over:
            notes.append("over: " + ", ".join(over))
        if fs >= FIRST_SENTENCE_TIP:
            notes.append(f"first sentence {fs}, not under {FIRST_SENTENCE_TIP}: put the main point in a shorter opener")
        if u != c:
            notes.append(f"emoji or symbols: {u} UTF-16 vs {c} code points")
        bad += bool(over or fs >= FIRST_SENTENCE_TIP)
        print(f"{n:3} {u:5} UTF-16 {c:5} cp  first sentence {fs:4}  " + ("; ".join(notes) or "OK"))
    label = f"{len(lines)} alt text" + ("" if len(lines) == 1 else "s")
    print(f"RESULT: {label}, {bad} to fix" if bad else f"RESULT: {label}, all fit")
    return 1 if bad else 0

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(__doc__.strip())
        sys.exit(2)
    sys.exit(main(sys.argv[1]))
