"""Validate a deliberately plain SRT subset and export a browser VTT track."""
from __future__ import annotations

import argparse
import hashlib
import json
import re
from pathlib import Path

import pysubs2

STAMP = r"\d{2}:[0-5]\d:[0-5]\d,\d{3}"
TIME = re.compile(rf"{STAMP} --> {STAMP}")
BLOCK = re.compile(rf"([1-9]\d*)\n({STAMP} --> {STAMP})\n([^\n]+(?:\n[^\n]+)*)")


def load_plain(path: Path):
    if path.stat().st_size > 1_000_000:
        raise ValueError("SRT exceeds exercise size limit")
    raw = path.read_text(encoding="utf-8-sig").replace("\r\n", "\n").replace("\r", "\n").strip()
    if not raw or "\ufffd" in raw or "```" in raw:
        raise ValueError("Empty, damaged or Markdown-wrapped SRT")
    # The library handles subtitle timing/text. This gate limits the supported plain-file contract.
    blocks = raw.split("\n\n")
    records = []
    for block in blocks:
        match = BLOCK.fullmatch(block)
        if not match:
            raise ValueError("Expected number, exact millisecond time line, text and a blank separator")
        index, stamp, text = match.groups()
        if any(char in text for char in "<>{}\\") or not text.strip():
            raise ValueError("Styled or empty captions are outside this exercise")
        records.append((int(index), stamp, text))
    if not 1 <= len(records) <= 1000:
        raise ValueError("Expected 1 to 1000 captions")
    if [row[0] for row in records] != list(range(1, len(records) + 1)):
        raise ValueError("Caption indices must be consecutive from 1")
    subtitles = pysubs2.SSAFile.from_string(raw, format_="srt")
    if len(subtitles) != len(records):
        raise ValueError("Parsed caption count mismatch")
    previous_end = 0
    for event, record in zip(subtitles, records):
        if event.start < previous_end or event.end <= event.start:
            raise ValueError("Overlapping, reversed or empty intervals are outside this exercise")
        if event.plaintext.strip() != record[2].strip():
            raise ValueError("Subtitle parser changed plain text")
        previous_end = event.end
    return raw, records, subtitles


def validate(source: Path, target: Path):
    raw_source, source_records, source_subs = load_plain(source)
    raw_target, target_records, target_subs = load_plain(target)
    if [(r[0], r[1]) for r in source_records] != [(r[0], r[1]) for r in target_records]:
        raise ValueError("Caption count, indices or literal time lines changed")
    if [(e.start, e.end) for e in source_subs] != [(e.start, e.end) for e in target_subs]:
        raise ValueError("Parsed time intervals changed")
    rows = []
    for index, stamp, text in target_records:
        lines = text.splitlines()
        rows.append({"index": index, "time_line": stamp, "lines": len(lines),
                     "characters_per_line": [len(line) for line in lines],
                     "needs_layout_review": len(lines) > 2 or any(len(line) > 42 for line in lines)})
    return raw_source, raw_target, target_subs, {
        "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
        "target_sha256": hashlib.sha256(target.read_bytes()).hexdigest(),
        "captions": len(rows), "literal_time_lines_unchanged": True,
        "indices_unchanged": True, "pysubs2": pysubs2.__version__, "rows": rows,
        "layout_flags": sum(row["needs_layout_review"] for row in rows),
        "limits_are_editorial": True, "meaning_verified_by_script": False,
        "audio_or_video_alignment_verified_by_script": False,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source", type=Path)
    parser.add_argument("translation", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    if args.output.exists():
        raise ValueError("Output folder exists; choose a new folder")
    _, _, subtitles, report = validate(args.source, args.translation)
    args.output.mkdir(parents=True)
    subtitles.save(str(args.output / "translation-ru.vtt"), encoding="utf-8", format_="vtt")
    report["output_vtt"] = "translation-ru.vtt"
    (args.output / "validation.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"captions": report["captions"], "times_unchanged": True,
                      "layout_flags": report["layout_flags"], "output": str(args.output)}, ensure_ascii=False))


if __name__ == "__main__":
    try:
        main()
    except (ValueError, OSError, UnicodeError) as error:
        raise SystemExit(str(error)) from error
