#!/usr/bin/env python3
"""Checks an SRT file against the SDH rules we read in the Netflix English (USA) Timed Text Style Guide (section I).
Usage: python3 sdh-lint.py file.srt   (exit 0 = no findings, 1 = findings printed one per line)"""
import re, sys
def secs(t):
    h, m, s = t.replace(",", ".").split(":"); return int(h) * 3600 + int(m) * 60 + float(s)
def cues(path):
    text = open(path, encoding="utf-8-sig").read().replace("\r\n", "\n")
    for block in re.split(r"\n\s*\n", text.strip()):
        rows = block.split("\n")
        m = re.match(r"(\S+) --> (\S+)", rows[1] if len(rows) > 1 else "")
        if m: yield rows[0].strip(), secs(m.group(1)), secs(m.group(2)), rows[2:]
found, prev_end = [], 0.0
for num, a, b, lines in cues(sys.argv[1]):
    f = lambda msg: found.append(f"cue {num}: {msg}")
    if len(lines) > 2: f(f"{len(lines)} lines, the limit is 2")
    for l in lines:
        plain = re.sub(r"<[^>]+>", "", l)
        if len(plain) > 42: f(f"line of {len(plain)} characters, the limit is 42: {plain!r}")
        if re.fullmatch(r"-?\s*\([^)]*\)", plain.strip()) or re.match(r"^[A-Z][A-Z ]{2,}:", plain): f(f"label not in square brackets: {plain!r}")
        if re.search(r"<i>\s*-?\s*\[", l): f(f"speaker ID or sound effect in italics: {plain!r}")
        if re.match(r"^-\s", plain): f(f"hyphen followed by a space (use '-' directly before the text): {plain!r}")
        if "..." in plain: f("three dots instead of the single ellipsis character U+2026")
    if len(lines) == 2 and sum(l.lstrip().startswith("-") for l in lines) == 1: f("only one of the two lines starts with a hyphen")
    if a < prev_end: f(f"starts at {a:.3f}s before the previous cue ends at {prev_end:.3f}s")
    prev_end = max(prev_end, b)
print("\n".join(found) if found else "no findings")
sys.exit(1 if found else 0)
