#!/usr/bin/env python3
"""Check a translated WebVTT file against its source, and copy back what a
translation tool dropped: header text, STYLE and REGION blocks, and cue settings.

Standard library only. Python 3.8+.

  python3 vtt_carry_settings.py check   source.vtt translated.vtt
  python3 vtt_carry_settings.py restore source.vtt translated.vtt out.vtt [--keep-notes]

`restore` matches cues by position and refuses to run unless both files have
the same number of cues with the same start and end times. It never changes
cue text. Blocks already present in the translated file (for example an RTL
STYLE block) are kept, and the source blocks are added after them.
"""
import re
import sys

TIMING = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)(.*)$")
TAG = re.compile(r"<(/?)(v|c|i|b|u|ruby|rt|lang)((?:\.[\w-]+)*)(?=[\s>])[^>]*>")
BARE = re.compile(r"&(?!#?\w+;)|<(?!/?[a-zA-Z][^<>]*>|[\d:.]+>)")


def seconds(ts):
    parts = ts.split(":")
    sec = float(parts[-1])
    mins = int(parts[-2]) if len(parts) > 1 else 0
    hours = int(parts[-3]) if len(parts) > 2 else 0
    return round(hours * 3600 + mins * 60 + sec, 3)


def parse(path):
    with open(path, encoding="utf-8-sig") as f:
        text = f.read().replace("\r\n", "\n").replace("\r", "\n")
    blocks = [b for b in re.split(r"\n{2,}", text.strip("\n")) if b.strip()]
    if not blocks or not blocks[0].startswith("WEBVTT"):
        sys.exit(f"{path}: first line is not WEBVTT")
    doc = {"header": blocks[0], "style": [], "region": [], "notes": [], "cues": []}
    for block in blocks[1:]:
        lines = block.split("\n")
        first = lines[0]
        if re.match(r"NOTE(\s|$)", first):
            doc["notes"].append((len(doc["cues"]), block))
            continue
        if first == "STYLE" and not doc["cues"]:
            doc["style"].append(block)
            continue
        if first == "REGION" and not doc["cues"]:
            doc["region"].append(block)
            continue
        cue_id = ""
        if "-->" not in first:
            cue_id, lines = first, lines[1:]
        match = TIMING.match(lines[0]) if lines else None
        if not match:
            print(f"{path}: skipped a block that is not a cue: {first!r}")
            continue
        doc["cues"].append({
            "id": cue_id,
            "start": match.group(1),
            "end": match.group(2),
            "settings": match.group(3).strip(),
            "text": "\n".join(lines[1:]),
        })
    return doc


def tags(text):
    """Tag names and classes, ignoring voice names and language codes."""
    return sorted(f"<{m.group(1)}{m.group(2)}{m.group(3)}>" for m in TAG.finditer(text))


def check(src, dst):
    problems = []
    if len(src["cues"]) != len(dst["cues"]):
        problems.append(f"cue count: source {len(src['cues'])}, translated {len(dst['cues'])}")
    if src["header"].split("\n")[0] != dst["header"].split("\n")[0]:
        problems.append(f"header text: source {src['header'].splitlines()[0]!r}, translated {dst['header'].splitlines()[0]!r}")
    for kind in ("style", "region"):
        if len(src[kind]) > len(dst[kind]):
            problems.append(f"{kind.upper()} blocks: source {len(src[kind])}, translated {len(dst[kind])}")
    if len(src["notes"]) != len(dst["notes"]):
        problems.append(f"NOTE blocks: source {len(src['notes'])}, translated {len(dst['notes'])} (comments; optional)")
    for n, (a, b) in enumerate(zip(src["cues"], dst["cues"]), start=1):
        where = f"cue {n}" + (f" ({a['id']})" if a["id"] else "")
        if (seconds(a["start"]), seconds(a["end"])) != (seconds(b["start"]), seconds(b["end"])):
            problems.append(f"{where}: timing {a['start']} --> {a['end']} became {b['start']} --> {b['end']}")
        if a["id"] != b["id"]:
            problems.append(f"{where}: identifier {a['id']!r} became {b['id']!r}")
        if a["settings"] != b["settings"]:
            problems.append(f"{where}: settings {a['settings'] or '(none)'!r} became {b['settings'] or '(none)'!r}")
        if tags(a["text"]) != tags(b["text"]):
            problems.append(f"{where}: tags {tags(a['text'])} became {tags(b['text'])}")
        if BARE.search(b["text"]):
            problems.append(f"{where}: unescaped & or < in translated text")
        if "-->" in b["text"]:
            problems.append(f"{where}: translated text contains -->, which ends a cue early")
        if not b["text"].strip():
            problems.append(f"{where}: translated text is empty")
    for p in problems:
        print(p)
    print(f"{len(problems)} problem(s) in {len(dst['cues'])} cues")
    return problems


def restore(src, dst, keep_notes):
    if len(src["cues"]) != len(dst["cues"]):
        sys.exit("cue counts differ; restore needs a one-to-one cue match")
    for n, (a, b) in enumerate(zip(src["cues"], dst["cues"]), start=1):
        if (seconds(a["start"]), seconds(a["end"])) != (seconds(b["start"]), seconds(b["end"])):
            sys.exit(f"cue {n}: timings differ; restore would attach settings to the wrong cue")
    out = [src["header"]]
    out += dst["style"] + [s for s in src["style"] if s not in dst["style"]]
    out += dst["region"] + [r for r in src["region"] if r not in dst["region"]]
    notes = {}
    for index, block in dst["notes"]:
        notes.setdefault(index, []).append(block)
    if keep_notes:
        for index, block in src["notes"]:
            if block not in notes.get(index, []):
                notes.setdefault(index, []).append(block)
    for n, (a, b) in enumerate(zip(src["cues"], dst["cues"])):
        out += notes.get(n, [])
        timing = f"{b['start']} --> {b['end']}" + (f" {a['settings']}" if a["settings"] else "")
        out.append("\n".join(([a["id"] or b["id"]] if (a["id"] or b["id"]) else []) + [timing, b["text"]]))
    out += notes.get(len(src["cues"]), [])
    return "\n\n".join(out) + "\n"


def main(argv):
    if len(argv) >= 3 and argv[0] == "check":
        sys.exit(1 if check(parse(argv[1]), parse(argv[2])) else 0)
    if len(argv) >= 4 and argv[0] == "restore":
        text = restore(parse(argv[1]), parse(argv[2]), "--keep-notes" in argv[4:])
        with open(argv[3], "w", encoding="utf-8") as f:
            f.write(text)
        print(f"wrote {argv[3]}")
        return
    sys.exit(__doc__)


if __name__ == "__main__":
    main(sys.argv[1:])
