"""Rebuild the synthetic course edit using Pillow, FFmpeg and libflite."""
from pathlib import Path
import json
import subprocess
from tempfile import TemporaryDirectory
from PIL import Image, ImageDraw, ImageFont

OUT = Path(__file__).resolve().parent
FONT = Path('/usr/share/fonts/truetype/dejavu')
SCENES = [
    ('Define the baseline', 'Capture the current process before you change it.',
     'Start by documenting the current process. A baseline gives you a reliable point of comparison after a change.', 6),
    ('Classify the findings', 'Separate missing values from inconsistent values.',
     'Then separate missing values from inconsistent values. Give each group a clear owner so an issue can be fixed and checked again.', 7),
    ('Close the review', 'Record the decision, owner and verification step.',
     'Close the review by recording the decision, the owner, and the verification step. A second reviewer should be able to trace your reasoning.', 6),
]

def run(*args):
    return subprocess.check_output(args, stderr=subprocess.PIPE, text=True)

def font(size, bold=False):
    return ImageFont.truetype(str(FONT / ('DejaVuSans-Bold.ttf' if bold else 'DejaVuSans.ttf')), size)

def slide(path, number, title, body):
    image = Image.new('RGB', (1280, 720), '#0c1528')
    draw = ImageDraw.Draw(image)
    draw.rounded_rectangle((48, 58, 874, 662), 32, fill='#152743', outline='#42628d', width=2)
    draw.text((92, 103), f'OPERATIONS TRAINING  /  {number:02d}', font=font(23, True), fill='#94ead2')
    draw.text((92, 195), title, font=font(53, True), fill='#f4f8ff')
    words = body.split()
    lines = ['']
    for word in words:
        candidate = f'{lines[-1]} {word}'.strip()
        if draw.textlength(candidate, font=font(37)) > 700 and lines[-1]:
            lines.append(word)
        else:
            lines[-1] = candidate
    draw.multiline_text((94, 328), '\n'.join(lines), font=font(37), fill='#e2edff', spacing=13)
    draw.rounded_rectangle((900, 58, 1232, 662), 32, fill='#23375b')
    draw.ellipse((989, 167, 1143, 321), fill='#a6b8ff')
    draw.rounded_rectangle((963, 345, 1169, 455), 48, fill='#8a9df4')
    draw.text((936, 521), 'Instructor area', font=font(29, True), fill='#f4f8ff')
    draw.text((936, 571), 'Synthetic placeholder', font=font(21), fill='#d0dcf4')
    image.save(path)

def stamp(seconds):
    ms = round(seconds * 1000)
    return f'{ms // 3600000:02}:{ms // 60000 % 60:02}:{ms // 1000 % 60:02}.{ms % 1000:03}'

def build():
    timeline = []
    localized_start = 0
    original_start = 0
    with TemporaryDirectory() as tmp:
        work = Path(tmp)
        for number, (title, body, narration, original_length) in enumerate(SCENES, 1):
            speech = work / f'{number}.txt'
            wave = work / f'{number}.wav'
            picture = work / f'{number}.png'
            speech.write_text(narration)
            slide(picture, number, title, body)
            run('ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', f'flite=textfile={speech}:voice=slt', str(wave))
            duration = float(run('ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                                 '-of', 'default=nk=1:nw=1', str(wave)).strip())
            # Whole-second boundaries keep the cue sheet and rendered scene cuts aligned.
            length = int(duration) + 2
            clip = work / f'{number}.mp4'
            run('ffmpeg', '-v', 'error', '-loop', '1', '-framerate', '24', '-i', str(picture),
                '-i', str(wave), '-t', str(length), '-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
                '-pix_fmt', 'yuv420p', '-af', 'loudnorm=I=-18:TP=-2:LRA=7,adelay=250,apad',
                '-ar', '48000', '-c:a', 'aac', '-b:a', '96k', str(clip))
            timeline.append(dict(scene=number, title=title, originalStart=original_start,
                                 localizedStart=localized_start, localizedEnd=localized_start + length,
                                 captionStart=localized_start + .25,
                                 captionEnd=round(localized_start + .25 + duration, 3),
                                 narration=narration))
            localized_start += length
            original_start += original_length
        clips = work / 'clips.txt'
        clips.write_text(''.join(f"file '{work / (str(row['scene']) + '.mp4')}'\n" for row in timeline))
        run('ffmpeg', '-y', '-v', 'error', '-f', 'concat', '-safe', '0', '-i', str(clips),
            '-c', 'copy', '-movflags', '+faststart', str(OUT / 'localized-lesson.mp4'))
    (OUT / 'timeline.json').write_text(json.dumps(timeline, indent=2) + '\n')
    cues = []
    for row in timeline:
        first, second = row['narration'].split('. ', 1)
        start, end = row['captionStart'], row['captionEnd']
        # Split at the sentence break using word count as a timing estimate.
        split = start + (end - start) * len(first.split()) / len(row['narration'].split())
        for text, cue_start, cue_end in ((first + '.', start, split), (second, split, end)):
            cues.append(f"{len(cues) + 1}\n{stamp(cue_start)} --> {stamp(cue_end)}\n{text}\n")
    (OUT / 'captions.vtt').write_text('WEBVTT\n\n' + '\n'.join(cues))
    slide(OUT / 'poster.png', 1, SCENES[0][0], SCENES[0][1])

if __name__ == '__main__':
    build()
