#!/usr/bin/env python3
"""Check a LinkedIn draft against the 3,000-character post limit LinkedIn publishes.

Usage: python3 linkedin-post-check.py draft.txt [--limit N]

Counts the draft the way the Koldflux Word counter does (UTF-16 units, each line
break 1) and also as Python len() (code points). The check uses the larger count,
because LinkedIn does not say which one its post box uses. Windows line breaks are
counted as one, as a browser text box does. --limit sets another number, for
example 1250 for comments; LinkedIn does not publish that one (third-party figure).
One line break at the very end of the file is ignored (most editors add it on save);
anything after it counts.
Exit: 0 fits, 1 over the limit, 2 the file or --limit cannot be read.
Standard library only.
"""
import re
import sys

URL = re.compile(r"https?://\S+")


def main(argv):
    # a console or file that is not UTF-8 shows ? for an emoji instead of crashing
    sys.stdout.reconfigure(errors="replace")
    args = []
    for a in argv[1:]:
        args.extend(a.split("=", 1) if a.startswith("--limit=") else [a])
    limit = 3000
    if "--limit" in args:
        i = args.index("--limit")
        try:
            limit = int(args[i + 1])
        except (IndexError, ValueError):
            limit = 0
        if limit < 1:
            print("error: --limit needs a whole number above 0, for example --limit 1250")
            return 2
        del args[i:i + 2]
    if len(args) != 1:
        print(__doc__.strip().splitlines()[2])
        return 2
    path = args[0]
    try:
        raw = open(path, "rb").read()
    except OSError as e:
        print(f"error: cannot open {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
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    if text.endswith("\n"):
        text = text[:-1]  # editors add one final line break; you would not paste it
    if not text.strip():
        print(f"error: {path} has no text")
        return 2
    utf16 = len(text.encode("utf-16-le")) // 2
    points = len(text)
    used = max(utf16, points)
    breaks = text.count("\n")
    wide = sorted({c for c in text if ord(c) > 0xFFFF})
    urls = URL.findall(text)
    print(f"characters: {utf16} UTF-16 units (Word counter), {points} Python len()")
    print(f"line breaks: {breaks} (1 character each)")
    if wide:
        shown = " ".join(f"{c} U+{ord(c):04X}" for c in wide[:8])
        more = f" and {len(wide) - 8} more" if len(wide) > 8 else ""
        print(f"counted as 2 by the Word counter: {shown}{more}")
    for u in urls:
        print(f"link: {len(u)} characters: {u[:60]}{'...' if len(u) > 60 else ''}")
    if used <= limit:
        print(f"RESULT: fits, {limit - used} left of {limit}")
        return 0
    print(f"RESULT: over by {used - limit} (limit {limit})")
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
