#!/usr/bin/env python3
"""Check an Etsy listing title and tags against the limits on Etsy's Help Center (read 2026-11-30).

Usage: python3 etsy-listing-check.py listing.txt
listing.txt: line 1 is the title, every following non-empty line is one tag.
Lengths are UTF-16 units of the text as typed, the same count the Koldflux Word counter shows.
Exit code: 0 all checks pass, 1 a check fails, 2 the file cannot be used.
Beyond Etsy's list: the curly apostrophe ’ (U+2019) is not on it (Etsy lists ‘ and '); it gets a note, not a failure.
"""
import sys
import unicodedata

TITLE_MAX = 140  # "A listing's title can be up to 140 characters long."
TAG_MAX = 20     # "Each tag can contain up to 20 characters."
TAGS_MAX = 13    # "You can use up to 13 tags per listing."
NO_START = {"'", "‘", "’", "-"}  # "cannot start your tag with these characters"
CURLY = "’"  # phones type it; Etsy's list has ‘ and ' but not this one
# "You can use the following special characters:" (same Etsy page), copied as listed
SPECIAL = set("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØŒÙÚÛÜÝÞßàáâãäåæçèéêëìíîïñòóôõöøœùúûüýþÿ'‘-")
ASCII = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ")


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


def tag_problem(tag):
    # the character list is checked on the composed form, so a decomposed é matches Etsy's é
    tag = unicodedata.normalize("NFC", tag)
    if tag[0] in NO_START:
        return "starts with " + repr(tag[0])
    for ch in tag:
        if ch in ASCII or ch in SPECIAL or ch == CURLY:
            continue
        return "character " + repr(ch) + " (U+%04X) is not on Etsy's list" % ord(ch)
    return None


def main():
    if len(sys.argv) != 2:
        print("usage: python3 etsy-listing-check.py listing.txt", file=sys.stderr)
        return 2
    try:
        with open(sys.argv[1], encoding="utf-8-sig") as f:
            text = f.read()
    except FileNotFoundError:
        print("stop: file not found: " + sys.argv[1], file=sys.stderr)
        return 2
    except UnicodeDecodeError:
        print("stop: the file is not UTF-8 text; save it as UTF-8 and run again", file=sys.stderr)
        return 2
    raw = [line.strip() for line in text.splitlines()]
    if not any(raw):
        print("stop: the file is empty; put the title on line 1 and one tag per line", file=sys.stderr)
        return 2
    if not raw[0]:
        print("stop: line 1 is empty; put the title on line 1 and one tag per line", file=sys.stderr)
        return 2
    title, tags = raw[0], [line for line in raw[1:] if line]
    fail = False
    cp, u16 = counts(title)
    flag = "OK" if u16 <= TITLE_MAX else "OVER"
    fail |= flag == "OVER"
    print("title: %d UTF-16 units (Word counter), %d Python len(), limit %d: %s" % (u16, cp, TITLE_MAX, flag))
    if cp != u16:
        print("  note: emoji make the two counts differ; the check uses the larger, UTF-16")
    composed = unicodedata.normalize("NFC", title)
    if composed != title:
        print("  note: accents typed as letter plus mark; joined they would be %d UTF-16 units" % counts(composed)[1])
    if len(tags) > TAGS_MAX:
        fail = True
        print("tags: %d, limit %d: OVER (lengths in UTF-16 units)" % (len(tags), TAGS_MAX))
    else:
        print("tags: %d of %d (lengths in UTF-16 units)" % (len(tags), TAGS_MAX))
    for i, tag in enumerate(tags, 1):
        u16 = counts(tag)[1]
        problems = []
        if u16 > TAG_MAX:
            problems.append("over the limit of %d" % TAG_MAX)
        p = tag_problem(tag)
        if p:
            problems.append(p)
        fail |= bool(problems)
        if problems:
            status = "; ".join(problems)
        elif CURLY in tag:
            status = "note: curly ’ is not on Etsy's list (it lists ‘ and '); untested on Etsy's form"
        else:
            status = "OK"
        print("  %2d %-22s %2d  %s" % (i, tag, u16, status))
    print("RESULT: " + ("FIX the lines marked above" if fail else "all checks pass"))
    return 1 if fail else 0


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