#!/usr/bin/env python3
"""Count YouTube titles and descriptions three ways and compare with the published limits.
Title limit: 100 characters. Description limit: 5,000 characters in YouTube Help, 5000 bytes in the Data API.
Which unit the YouTube app counts a title in is not documented, so this prints all three.
Usage:
  python3 check-yt.py titles.txt                         one title per line (blank and spaces-only lines are skipped, so item N is the Nth line used)
  python3 check-yt.py --kind description desc.txt        the whole file is one description
  python3 check-yt.py --csv sheet.csv --column Title     a spreadsheet export (UTF-8, header row)
  add --keyword "text" to print the position (in code points, from 1) where the key words start in each item
Exit code: 0 all fine, 1 at least one item over or in doubt, 2 usage or file error."""
import argparse, csv, io, re, sys

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

def title_verdict(s):
    cp, u16, _ = counts(s)
    bad = [c for c in '<>' if c in s]
    if bad:
        return 'FAIL', 'contains ' + ' '.join(bad) + ' (the Data API forbids < and >)'
    if cp > 100:
        return 'OVER', 'more than 100 by every count'
    if u16 > 100:
        return 'CHECK', 'fits by code points, over 100 by UTF-16 units'
    return 'OK', 'at most 100 by every count'

def desc_verdict(s):
    cp, u16, b = counts(s)
    bad = [c for c in '<>' if c in s]
    if bad:
        return 'FAIL', 'contains ' + ' '.join(bad) + ' (the Data API forbids < and >)'
    if cp > 5000:
        return 'OVER', 'more than 5,000 characters'
    if u16 > 5000:
        more = " and over the API's 5000 bytes" if b > 5000 else ''
        return 'CHECK', 'fits by code points, over 5,000 by UTF-16 units' + more
    if b > 5000:
        return 'API-OVER', "within Help's 5,000 characters but over the API's 5000 bytes"
    return 'OK', 'under both limits'

def main():
    ap = argparse.ArgumentParser(add_help=True)
    ap.add_argument('file')
    ap.add_argument('--kind', choices=['title', 'description'], default='title')
    ap.add_argument('--csv', action='store_true')
    ap.add_argument('--column')
    ap.add_argument('--keyword')
    a = ap.parse_args()
    try:
        raw = open(a.file, encoding='utf-8-sig', newline='').read()
    except (OSError, UnicodeDecodeError) as e:
        print('error: cannot read', a.file, '(' + str(e) + ')'); return 2
    if a.csv:
        if not a.column:
            print('error: --csv needs --column NAME'); return 2
        rows = list(csv.DictReader(io.StringIO(raw, newline='')))
        if not rows or a.column not in rows[0]:
            print('error: column', a.column, 'not found'); return 2
        items = [r[a.column] for r in rows]
    elif a.kind == 'description':
        items = [raw]
    else:
        items = [l for l in raw.replace('\r\n', '\n').split('\n') if l.strip() != '']
    if a.kind == 'description' and not a.csv and not raw.strip():
        items = []
    if not items:
        print('error: nothing to check in', a.file); return 2
    worst = 0
    verdict = title_verdict if a.kind == 'title' else desc_verdict
    for i, s in enumerate(items, 1):
        cp, u16, b = counts(s)
        v, why = verdict(s)
        kw = ''
        if a.keyword:
            m = re.search(re.escape(a.keyword), s, re.IGNORECASE)
            kw = (' | keyword starts at code point ' + str(m.start() + 1) if m else ' | keyword not found')
        print(f'{v} | item {i} | {cp} code points | {u16} UTF-16 units | {b} UTF-8 bytes | {why}{kw}')
        if v != 'OK':
            worst = 1
    return worst

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