#!/usr/bin/env python3
"""Check a set of translated subtitle files against their source.

Usage: python3 check_subtitle_set.py SOURCE.srt TRANSLATED.srt [TRANSLATED.srt ...]

Reads SRT or WebVTT. For each translated file it checks that the file is
UTF-8, has the same number of cues as the source, uses the same start and end
time for every cue, has no empty cues, and is named <base>.<language>[.flag].<ext>
with the same base as the source. Standard library only.
"""
import re
import sys
from pathlib import Path

TIME = re.compile(r"(\d{1,2}:)?(\d{2}):(\d{2})[,.](\d{3})")
ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
# 2-3 letter primary language, optional script (4 letters) and region (2 letters or 3 digits)
LANG = re.compile(r"^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|\d{3}))?$")
FLAGS = {"default", "forced", "foreign", "sdh", "cc"}
NOT_LANGUAGE_CODES = {"jp": "ja", "cn": "zh", "gr": "el", "dk": "da", "ua": "uk", "cz": "cs"}


def ms(stamp):
    m = TIME.fullmatch(stamp)
    if not m:
        raise ValueError(f"bad timestamp {stamp!r}")
    h = int(m.group(1)[:-1]) if m.group(1) else 0
    return ((h * 60 + int(m.group(2))) * 60 + int(m.group(3))) * 1000 + int(m.group(4))


def read_cues(path):
    raw = path.read_bytes()
    problems = []
    if raw.startswith(b"\xef\xbb\xbf"):
        problems.append("starts with a UTF-8 BOM (most players accept it; strip it if one does not)")
        raw = raw[3:]
    try:
        text = raw.decode("utf-8")
    except UnicodeDecodeError as err:
        return None, [f"not valid UTF-8 (byte {err.start}); re-save the file as UTF-8"]
    cues = []
    for block in re.split(r"\n\s*\n", text.replace("\r\n", "\n").strip()):
        lines = block.split("\n")
        for i, line in enumerate(lines):
            m = ARROW.match(line)
            if m:
                cues.append((ms(m.group(1)), ms(m.group(2)), "\n".join(lines[i + 1:]).strip()))
                break
    return cues, problems


def split_name(path):
    parts = path.name.split(".")
    return parts[0], parts[1:-1], parts[-1]


def main(argv):
    if len(argv) < 3:
        print(__doc__)
        return 2
    source = Path(argv[1])
    src_cues, src_problems = read_cues(source)
    if src_cues is None:
        print(f"{source.name}: {src_problems[0]}")
        return 1
    src_base, _, _ = split_name(source)
    print(f"source {source.name}: {len(src_cues)} cues")
    failed = 0
    seen = {}
    for name in argv[2:]:
        path = Path(name)
        cues, problems = read_cues(path)
        base, tags, _ = split_name(path)
        if base != src_base:
            problems.append(f"base name {base!r} differs from source {src_base!r}; players match by base name")
        langs = [t for t in tags if t.lower() not in FLAGS]
        if not langs:
            problems.append("no language code in the file name")
        else:
            lang = langs[0]
            key = lang.lower()
            if lang.lower() in NOT_LANGUAGE_CODES:
                problems.append(f"{lang!r} is a country code, not a language code; use {NOT_LANGUAGE_CODES[lang.lower()]!r}")
            elif not LANG.match(lang):
                problems.append(f"{lang!r} is not a language tag such as 'es', 'pt-BR' or 'zh-Hant'")
            if key == "hi" and len(tags) == 1:
                problems.append("'hi' alone means Hindi; for hearing-impaired subtitles use '<lang>.sdh'")
            if key in seen:
                problems.append(f"language {lang!r} already used by {seen[key]}")
            seen[key] = path.name
        if cues is not None:
            if len(cues) != len(src_cues):
                problems.append(f"{len(cues)} cues, source has {len(src_cues)}")
            for i, (a, b) in enumerate(zip(src_cues, cues), 1):
                if a[:2] != b[:2]:
                    problems.append(f"cue {i} timing {b[0]}-{b[1]} ms, source {a[0]}-{a[1]} ms")
                if not b[2]:
                    problems.append(f"cue {i} is empty")
        status = "OK" if not problems else "CHECK"
        failed += bool(problems)
        print(f"{status:5} {path.name}")
        for p in problems:
            print(f"      - {p}")
    return 1 if failed else 0


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