#!/usr/bin/env python3

import datetime
import sys

import yaml

splits = yaml.safe_load(open(sys.argv[1]))

for s in splits:
    duration_opt = ""
    if "end" in s:
        start = s.get("start", "00:00:00")
        duration = datetime.datetime.fromisoformat(
            f'1970-01-01 {s["end"]}'
        ) - datetime.datetime.fromisoformat(f"1970-01-01 {start}")
        duration_opt = f"-t {duration}"
    start_opt = ""
    if "start" in s:
        start_opt = f'-ss {s["start"]}'
    author_opt = ""
    authors = ""
    if "who" in s:
        authors = "; ".join(s.get("who"))
        author_opt = f'-metadata "author={authors}"'
    print(
        f'ffprobe=`ffprobe -v quiet -print_format json -select_streams v -show_format -show_streams {s["srcfile"]}`'
    )
    print(f'width=`jq ".streams[0].width" <<<$ffprobe`')
    print(f'height=`jq ".streams[0].height" <<<$ffprobe`')
    print(
        f'sed -e "s/@AUTHOR@/{authors}/" -e "s/@TITLE@/{s["title"]}/" title-template-${{width}}x${{height}}.svg > output/titles/{s["output"]}.svg'
    )
    print(
        f'inkscape -o output/titles/{s["output"]}.png output/titles/{s["output"]}.svg'
    )
    print(
        f'ffmpeg -y -loop 1 -r 25 -t 5 -i output/titles/{s["output"]}.png {start_opt} -i {s["srcfile"]} {duration_opt} -movflags faststart -metadata "title={s["title"]}" {author_opt} -metadata "year=2021" -metadata "show=SWH5YEARS" -filter_complex "[0:v]fade=t=out:st=4:d=1:alpha=1[v0]; [1:v][v0]overlay=eof_action=pass:repeatlast=false:shortest=false[v]" -map "[v]" -map 1:a -map_chapters -1 -c:v libx264 -preset slow -crf 18  -pix_fmt yuv420p -c:a libopus -b:a 128k output/{s["output"]}.mp4'
    )
    print()
