#!/usr/bin/env python3
"""Count a YouTube tag list by the rule in the YouTube Data API videos resource (snippet.tags[]):
max 500 characters, commas between tags count, a tag containing a space counts two quotation marks.

Usage: python3 count-tags.py tags.txt            count the list
       python3 count-tags.py --fit tags.txt      also print the tags that fit when you keep them in order
Input: tags separated by commas, or one tag per line (or both). Blank entries are ignored.
Exit codes: 0 within 500, 1 over 500, 2 the file could not be read or holds no tags.
"""
import sys

LIMIT = 500


def read_tags(path):
    try:
        with open(path, encoding="utf-8-sig", newline="") as f:
            text = f.read()
    except (OSError, UnicodeDecodeError) as e:
        print(f"error: cannot read {path} ({e})")
        sys.exit(2)
    text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\n", ",")
    tags = [t.strip() for t in text.split(",")]
    return [t for t in tags if t]


def cost(tag):
    # characters (code points) plus two quotation marks when the tag has a space
    return len(tag) + (2 if " " in tag else 0)


def total(tags):
    return sum(cost(t) for t in tags) + max(0, len(tags) - 1)


def main(argv):
    fit = "--fit" in argv
    args = [a for a in argv if a != "--fit"]
    if len(args) != 1:
        print("usage: python3 count-tags.py [--fit] tags.txt")
        sys.exit(2)
    tags = read_tags(args[0])
    if not tags:
        print(f"error: no tags found in {args[0]}")
        sys.exit(2)
    n = total(tags)
    quoted = sum(1 for t in tags if " " in t)
    print(f"tags: {len(tags)}, with a space: {quoted}, commas: {len(tags) - 1}")
    print(f"total {n} of {LIMIT} characters")
    if n <= LIMIT:
        print(f"OK, within the limit, {LIMIT - n} to spare")
    else:
        print(f"OVER by {n - LIMIT} characters")
    if fit:
        kept, used = [], 0
        for t in tags:
            add = cost(t) + (1 if kept else 0)
            if used + add > LIMIT:
                break
            kept.append(t)
            used += add
        print(f"kept {len(kept)} of {len(tags)} tags, {used} characters:")
        print(", ".join(kept) if kept else "(no tag fits)")
        if len(kept) < len(tags):
            print("dropped: " + ", ".join(tags[len(kept):]))
    sys.exit(0 if n <= LIMIT else 1)


main(sys.argv[1:])
