#!/usr/bin/env python3
"""Count the hashtags in a caption file and compare the count with the limits read on the platforms' help pages.

usage: python3 hashtag-check.py caption.txt
A hashtag is a # followed by letters, combining marks, digits or underscores in any alphabet (the rule of the Koldflux Hashtag counter).
For YouTube, put the title and the description in the file together: the help page counts hashtags on the video.
"""
import sys
import unicodedata

# limits as stated on the help pages read on 2026-11-24 (see the guide); None = no number found on the page read
LIMITS = [
    ("Instagram (Help Center: up to 5 tags on a post)", 5),
    ("YouTube (Help: more than 60 hashtags are all ignored)", 60),
    ("TikTok (page read names no number)", None),
    ("LinkedIn (hashtag help page not readable that day)", None),
]


def hashtags_of(text):
    tags, i, n = [], 0, len(text)
    while i < n:
        if text[i] != "#":
            i += 1
            continue
        j = i + 1
        while j < n and (text[j] == "_" or unicodedata.category(text[j])[0] in "LMN"):
            j += 1
        if j > i + 1:
            tags.append(text[i:j])
        i = max(j, i + 1)
    return tags


def main():
    if len(sys.argv) != 2:
        sys.exit("usage: python3 hashtag-check.py caption.txt")
    try:
        with open(sys.argv[1], encoding="utf-8") as f:
            text = f.read().replace("\r\n", "\n").replace("\r", "\n")
    except FileNotFoundError:
        sys.exit("file not found: " + sys.argv[1])
    except UnicodeDecodeError:
        sys.exit("the file is not UTF-8 text: " + sys.argv[1])
    except OSError:
        sys.exit("cannot read: " + sys.argv[1])
    if not text.strip():
        sys.exit("the file is empty: " + sys.argv[1])
    tags = hashtags_of(text)
    unique = len({t.lower() for t in tags})
    print(f"hashtags: {len(tags)} (unique, ignoring capitals: {unique})")
    print("list: " + (" ".join(tags) if tags else "none"))
    for name, limit in LIMITS:
        if limit is None:
            print(f"  {name}: no limit to check")
        elif len(tags) > limit:
            print(f"  {name}: OVER by {len(tags) - limit}")
        else:
            print(f"  {name}: ok, {limit - len(tags)} left")


main()
