#!/usr/bin/env python3
"""Builds film-outro/: the last seconds of film-codex alone, to review the ending."""
import os, re, shutil
S, D, L = "film-codex", "film-outro", 11.3
shutil.rmtree(D, ignore_errors=True)
shutil.copytree(S, D, ignore=shutil.ignore_patterns("clips", ".hyperframes", "renders", "mix.m4a"))
html = open(f"{D}/index.html").read()
total = float(re.search(r'data-composition-id="main" data-start="0" data-duration="([\d.]+)"', html).group(1))
off = total - L
html = re.sub(r'\s*
', "", html)
html = re.sub(r"\s*
", "", html)
html = html.replace(f'data-duration="{total:.3f}"', f'data-duration="{L}"')
html = re.sub(r'(id="outro".*?data-start=")[\d.]+', lambda m: f"{m.group(1)}{L - 8.3}", html)
open(f"{D}/index.html", "w").write(html)
cues = open(f"{D}/assets/cues.js").read()
cues = re.sub(r"FILM_SECONDS = [\d.]+", f"FILM_SECONDS = {L}", cues)
items = re.findall(r"\{ t: ([\d.]+), (.*?) \}", cues)
kept = [f"{{ t: {max(0, float(t) - off):.3f}, {body} }}" for t, body in items]
cues = re.sub(r"window\.FIELD_CUES = \[.*\];", lambda m: "window.FIELD_CUES = [\n" + ",".join(kept) + "\n];", cues, flags=re.S)
open(f"{D}/assets/cues.js", "w").write(cues)