#!/usr/bin/env python3
"""Check an SRT or WebVTT transcript file before you publish it.
Usage: python3 check-transcript.py transcript.vtt [audio-seconds]
Exit 0 = no problems found (warnings may be printed), 1 = problems listed, 2 = file missing/empty/unreadable or bad audio length.
Checks: VTT starts with WEBVTT; time format (VTT uses a dot, SRT a comma); end after start; cues start in order;
no empty cue text; last cue ends no more than 1 s after the audio length (if given).
Overlapping cues are only a WARNING (WebVTT allows overlap): look at them, the exit code does not change."""
import math, re, sys

def secs(h, m, s, f): return int(h) * 3600 + int(m) * 60 + int(s) + int(f.ljust(3, "0")[:3]) / 1000

def main(argv):
    if len(argv) not in (2, 3): print("usage: check-transcript.py transcript.(srt|vtt) [audio-seconds]"); return 2
    path = argv[1]
    try: raw = open(path, "rb").read()
    except OSError as e: print(f"cannot open {path}: {e.strerror}"); return 2
    try: text = raw.decode("utf-8-sig")
    except UnicodeDecodeError: print("file is not UTF-8 text (save it as UTF-8)"); return 2
    if not text.strip(): print(f"{path} is empty"); return 2
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    is_vtt = text.lstrip().startswith("WEBVTT")
    if path.lower().endswith(".vtt") and not is_vtt: print("PROBLEM: a .vtt file must start with the line WEBVTT")
    problems = 0 if (is_vtt or not path.lower().endswith(".vtt")) else 1
    sep = r"\." if is_vtt else ","
    tre = re.compile(rf"^(?:(\d+):)?(\d{{2}}):(\d{{2}}){sep}(\d{{3}}) --> (?:(\d+):)?(\d{{2}}):(\d{{2}}){sep}(\d{{3}})")
    cues, prev_end, prev_start, i = 0, 0.0, 0.0, 0
    warnings = 0
    lines = text.split("\n")
    while i < len(lines):
        m = tre.match(lines[i].strip())
        if not m:
            if "-->" in lines[i]: print(f"PROBLEM line {i+1}: time line not in the {'WebVTT' if is_vtt else 'SRT'} format: {lines[i]!r}"); problems += 1
            i += 1; continue
        g = m.groups()
        start = secs(g[0] or 0, g[1], g[2], g[3]); end = secs(g[4] or 0, g[5], g[6], g[7])
        body = []; i += 1
        while i < len(lines) and lines[i].strip(): body.append(lines[i]); i += 1
        cues += 1
        if end <= start: print(f"PROBLEM cue {cues} (line {i}): ends at {end:.3f} s, not after its start {start:.3f} s"); problems += 1
        if start < prev_start - 0.001: print(f"PROBLEM cue {cues}: starts at {start:.3f} s, before the previous cue started ({prev_start:.3f} s): cues are out of order"); problems += 1
        elif start < prev_end - 0.001: print(f"WARNING cue {cues}: starts at {start:.3f} s before the previous cue ended ({prev_end:.3f} s): overlapping cues"); warnings += 1
        if not " ".join(body).strip(): print(f"PROBLEM cue {cues}: no text"); problems += 1
        prev_end = max(prev_end, end); prev_start = start
    if cues == 0: print("PROBLEM: no cues found"); problems += 1
    if len(argv) == 3:
        try: dur = float(argv[2])
        except ValueError: dur = float("nan")
        if not math.isfinite(dur) or dur <= 0: print("audio-seconds must be a number above 0"); return 2
        if prev_end > dur + 1: print(f"PROBLEM: last cue ends at {prev_end:.1f} s, audio is {dur:.1f} s long"); problems += 1
    print(f"{'PROBLEMS: ' + str(problems) if problems else 'OK'}{f' ({warnings} warning(s))' if warnings else ''}: {cues} cues, last one ends at {prev_end:.1f} s")
    return 1 if problems else 0

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