"""Apply translated text by cue number to a conventional UTF-8 SRT file."""
import argparse
import json
import re
from pathlib import Path

TIME = r"\d{2,}:\d{2}:\d{2},\d{3}"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("translations", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()

def unique_pairs(pairs):
    values = {}
    for key, value in pairs:
        if key in values:
            raise ValueError(f"Duplicate translation ID: {key}")
        values[key] = value
    return values

translations = json.loads(args.translations.read_text(encoding="utf-8"), object_pairs_hook=unique_pairs)
if not isinstance(translations, dict):
    parser.error("Translations must be a JSON object keyed by cue number")
cues = {}
for block in re.split(r"\n[ \t]*\n", args.source.read_text(encoding="utf-8-sig").strip()):
    parts = block.splitlines()
    if len(parts) < 3:
        parser.error("Incomplete subtitle cue")
    key, timing = parts[:2]
    if not re.fullmatch(r"[0-9]+", key) or key in cues or not re.fullmatch(f"{TIME} --> {TIME}", timing):
        parser.error(f"Invalid or repeated cue: {key}")
    cues[key] = timing
if cues.keys() != translations.keys():
    parser.error(f"Missing: {sorted(cues.keys() - translations.keys())}. Extra: {sorted(translations.keys() - cues.keys())}")
output = []
for key, timing in cues.items():
    value = translations[key]
    if not isinstance(value, str) or not value or any(not line.strip() for line in value.split("\n")) or "\r" in value:
        parser.error(f"Invalid translation text for cue {key}")
    output.append(f"{key}\n{timing}\n{value}")
with args.output.open("x", encoding="utf-8", newline="\n") as stream:
    stream.write("\n\n".join(output) + "\n")
print(f"Applied {len(output)} translations. Original timing lines preserved.")
