#!/usr/bin/env python3
"""List the characters a subtitle file uses, and (optionally) which of them a font has no glyph for.

Usage:
  python3 srt-chars.py subs.srt              prints every character outside plain ASCII, once each
  python3 srt-chars.py subs.srt font.ttf     also lists the ones font.ttf has no glyph for (needs: pip install fonttools)

Cue numbers (lines of ASCII digits only) and timecode lines are skipped. Works with UTF-8 files with or without a BOM
and with Windows (CRLF) line breaks. Exit code: 0 when every character is covered (or no font
was given), 1 when the font misses at least one character, 2 on an input problem.
"""
import re
import sys
import unicodedata

TIME = re.compile(r"^\s*\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}\s*-->")


def fail(msg):
    print("error:", msg, file=sys.stderr)
    sys.exit(2)


def read_text(path):
    try:
        raw = open(path, "rb").read()
    except FileNotFoundError:
        fail(f"file not found: {path}")
    except OSError as e:
        fail(f"cannot read {path}: {e.strerror}")
    if not raw.strip():
        fail(f"{path} is empty")
    try:
        text = raw.decode("utf-8-sig")
    except UnicodeDecodeError:
        fail(f"{path} is not UTF-8. Save it as UTF-8 in your editor and run again.")
    lines = []
    for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
        s = line.strip()
        if not s or (s.isascii() and s.isdigit()) or TIME.match(s):
            continue
        lines.append(s)
    return "".join(lines)


def main():
    if len(sys.argv) not in (2, 3):
        fail("usage: python3 srt-chars.py subs.srt [font.ttf]")
    text = read_text(sys.argv[1])
    chars = sorted({c for c in text if ord(c) > 0x7E})
    if not chars:
        print("Only plain ASCII characters in this file; any Latin font covers them.")
    else:
        print(f"{len(chars)} character{'' if len(chars) == 1 else 's'} outside plain ASCII:")
        print("".join(chars))
        nfd = [c for c in chars if unicodedata.combining(c)]
        if nfd:
            print(f"note: {len(nfd)} combining accent marks found; the file is not in NFC form.")
    if len(sys.argv) == 2:
        return
    try:
        from fontTools.ttLib import TTFont
    except ImportError:
        fail("the font check needs fontTools: pip install fonttools")
    try:
        cmap = TTFont(sys.argv[2], fontNumber=0).getBestCmap() or {}
    except FileNotFoundError:
        fail(f"font not found: {sys.argv[2]}")
    except Exception as e:
        fail(f"cannot read the font {sys.argv[2]}: {e}")
    used = sorted({c for c in text if not c.isspace()})
    missing = [c for c in used if ord(c) not in cmap]
    if not missing:
        print(f"The font has a glyph for all {len(used)} characters used.")
        return
    print(f"The font has no glyph for {len(missing)} of {len(used)} characters used:")
    for c in missing:
        print(f"  U+{ord(c):04X} {c} {unicodedata.name(c, '?')}")
    sys.exit(1)


if __name__ == "__main__":
    main()
