"""Export the Caption Fieldnotes reference JSON as SRT, WebVTT or timed WebVTT.

Usage: python3 convert.py studio-check-reference.json --format highlight > highlighted.vtt
The input uses seconds, a turns array, and a flat words array. Requires Python 3.9+.
"""
import argparse
import json
from html import escape
from pathlib import Path


def stamp(seconds, srt=False):
    millis = round(seconds * 1000)
    if millis < 0:
        raise ValueError("Timestamps must be nonnegative")
    minutes, remainder = divmod(millis, 60_000)
    hours, minutes = divmod(minutes, 60)
    sec, ms = divmod(remainder, 1000)
    separator = "," if srt else "."
    return f"{hours:02}:{minutes:02}:{sec:02}{separator}{ms:03}"


def export(data, form):
    srt = form == "srt"
    blocks = [] if srt else ["WEBVTT"]
    for index, turn in enumerate(data["turns"], start=1):
        start, end = turn["start"], turn["end"]
        if not 0 <= start < end:
            raise ValueError(f"Invalid bounds for cue {index}")
        timing = f"{stamp(start, srt)} --> {stamp(end, srt)}"
        speaker = escape(turn["speaker"], quote=False)
        if srt:
            blocks.append(f"{index}\n{timing}\n{speaker}: {escape(turn['text'], quote=False)}")
            continue
        text = escape(turn["text"], quote=False)
        if form == "highlight":
            words = [w for w in data["words"] if w["speaker"] == turn["speaker"] and start <= w["start"] < end]
            if not words or words[0]["start"] != start:
                raise ValueError(f"The first word of cue {index} must begin at the cue start")
            parts = [escape(words[0]["word"], quote=False)]
            previous = start
            for word in words[1:]:
                onset = word["start"]
                if round(onset * 1000) <= round(previous * 1000):
                    raise ValueError(f"Word starts in cue {index} must increase")
                parts.append(f"<{stamp(onset)}>{escape(word['word'], quote=False)}")
                previous = onset
            text = " ".join(parts)
        blocks.append(f"{timing}\n<v {speaker}>{text}</v>")
    return "\n\n".join(blocks) + "\n"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("reference", type=Path)
    parser.add_argument("--format", choices=("srt", "vtt", "highlight"), required=True)
    args = parser.parse_args()
    print(export(json.loads(args.reference.read_text(encoding="utf-8")), args.format), end="")


if __name__ == "__main__":
    main()
