"""Spot a film's English screenplay dialogue. Export a WebVTT track or a picture print with the same cues.

python3 kit/cinema-subtitles.py cues.json --vtt english.vtt
python3 kit/cinema-subtitles.py cues.json --burn clean.mp4 subtitled.mp4
Cue frames count from zero; the end is exclusive. Use --font to locate the archived News Cycle Bold.
"""
import argparse
import html
import json
import subprocess
import tempfile
from fractions import Fraction
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


FONT = Path(__file__).resolve().parent.parent / 'assets/fonts/news-cycle-normal-700.woff2'
EM_HEIGHT = .05
BOTTOM = .08
SAFE_WIDTH = .84
INK = '#f5f3ed'
EDGE = '#191917'


def timestamp(frame, fps):
    ms = round(1000 * frame / fps)
    seconds, ms = divmod(ms, 1000)
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return f'{hours:02}:{minutes:02}:{seconds:02}.{ms:03}'


def checked_cues(sheet):
    fps = sheet['fps']
    if type(fps) is not int or fps <= 0:
        raise ValueError('Use a positive integer frame rate.')
    last = 0
    for cue in sheet['cues']:
        start, end = cue['startFrame'], cue['endFrame']
        if type(start) is not int or type(end) is not int or start < last or start >= end:
            raise ValueError(f'Invalid or overlapping cue at frames {start}–{end}.')
        text = cue['screenplay']
        lines = cue.get('lines', [text])
        if not isinstance(text, str) or not text.strip() or not isinstance(lines, list) or not 1 <= len(lines) <= 2:
            raise ValueError('Each subtitle needs its screenplay text and one or two display lines.')
        if any(not isinstance(line, str) or not line.strip() or '\n' in line or '\r' in line for line in lines):
            raise ValueError('Specify display lines as separate nonempty strings.')
        if ' '.join(lines) != text:
            raise ValueError(f'The display lines must preserve the exact screenplay wording: {text}')
        yield start, end, lines
        last = end


def vtt(cues, fps):
    # Let the native track size scale with the video and the viewer’s caption preferences.
    style = (f'::cue {{ font-family: "News Cycle", sans-serif; font-weight: 700; '
             f'color: {INK}; background: transparent; '
             f'text-shadow: -.035em 0 .025em {EDGE}, .035em 0 .025em {EDGE}, '
             f'0 -.035em .025em {EDGE}, 0 .045em .045em {EDGE}; }}')
    blocks = ['WEBVTT', 'STYLE\n'+style]
    for a, b, lines in cues:
        timing = (f'{timestamp(a,fps)} --> {timestamp(b,fps)} line:{(1-BOTTOM)*100:g}%,end '
                  f'position:50% size:{SAFE_WIDTH*100:g}% align:center')
        blocks.append(timing + '\n' + '\n'.join(html.escape(line, quote=False) for line in lines))
    return '\n\n'.join(blocks) + '\n'


def card(lines, width, height, font):
    image = Image.new('RGBA', (width, height))
    draw = ImageDraw.Draw(image)
    em = max(1, round(height * EM_HEIGHT))
    face = ImageFont.truetype(str(font), em)
    if any(draw.textlength(line, font=face) > width * SAFE_WIDTH for line in lines):
        raise ValueError('Text exceeds the title-safe width. Rebreak the cue at a spoken phrase.')
    # Keep the bottom baseline stable for descenders and punctuation across cuts.
    descent = face.getmetrics()[1]
    last_baseline = round(height*(1-BOTTOM) - descent)
    leading = round(em*1.22)
    for i,line in enumerate(lines):
        baseline = last_baseline - (len(lines)-i-1)*leading
        draw.text((width//2,baseline),line,anchor='ms',font=face,fill=INK,
                  stroke_width=max(1,round(em*.035)),stroke_fill=EDGE)
    return image


def burn(cues, fps, clean, target, font):
    if clean.resolve() == target.resolve():
        raise ValueError('Choose a different output path to preserve the clean master.')
    streams = json.loads(subprocess.check_output([
        'ffprobe','-v','error','-select_streams','v:0','-show_streams','-of','json',clean
    ]))['streams']
    source = streams[0]
    width, height = source['width'], source['height']
    if Fraction(source['avg_frame_rate']) != fps or Fraction(source['r_frame_rate']) != fps:
        raise ValueError('Cue-sheet and movie frame rates differ.')
    count = int(source['nb_frames'])
    if cues and cues[-1][1] > count:
        raise ValueError('A subtitle runs past the end of the picture.')
    with tempfile.TemporaryDirectory(dir=target.parent) as scratch:
        folder = Path(scratch)
        clear = folder/'clear.png'
        Image.new('RGBA', (width,height)).save(clear)
        entries = []
        def hold(filename, frames):
            if frames:
                entries.extend((f"file '{filename}'",f'option framerate {fps}',f'duration {frames/fps:.9f}'))
        cursor = 0
        for i,(a,b,lines) in enumerate(cues):
            hold(clear.name,a-cursor)
            name = f'cue-{i:05}.png'
            card(lines,width,height,font).save(folder/name)
            hold(name,b-a)
            cursor = b
        hold(clear.name,count-cursor)
        entries.extend((f"file '{clear.name}'",f'option framerate {fps}'))
        playlist = folder/'titles.ffconcat'
        playlist.write_text('\n'.join(entries)+'\n')
        output = folder/'print.mp4'
        subprocess.run(['ffmpeg','-nostdin','-v','error','-y','-i',clean,'-f','concat','-safe','0','-i',playlist,
                        '-filter_complex','[0:v:0][1:v:0]overlay=eof_action=pass[v]',
                        '-map','[v]','-map','0:a?','-frames:v',str(count),'-c:v','libx264',
                        '-preset','slow','-crf','16','-threads','2','-pix_fmt','yuv420p','-c:a','copy',
                        '-movflags','+faststart',output],check=True)
        output.replace(target)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('sheet',type=Path)
    parser.add_argument('--vtt',type=Path)
    parser.add_argument('--burn',nargs=2,type=Path,metavar=('CLEAN_MOVIE','PRINT'))
    parser.add_argument('--font',type=Path,default=FONT)
    args = parser.parse_args()
    if not (args.vtt or args.burn):
        parser.error('Choose --vtt or --burn.')
    sheet = json.loads(args.sheet.read_text())
    cues = list(checked_cues(sheet))
    if args.burn:
        burn(cues,sheet['fps'],*args.burn,args.font)
    if args.vtt:
        args.vtt.write_text(vtt(cues,sheet['fps']))


if __name__ == '__main__':
    main()
