#!/usr/bin/env python3

# $1: source ep number

import json
import os
from pathlib import Path
import subprocess
import sys


this_dir = Path(__file__).parent
src_dir = this_dir.parent / "[Chyuu-PAS] Shoujo☆Kageki Revue Starlight [WEB 1080p EAC3]"
target_dir_template = this_dir.parent / "Folge {ep_num:02d}" / "english"
sub_template = target_dir_template / "[Chyuu-PAS] SKRS - {ep_num:02d}.ass"
font_dir_template = target_dir_template / "cpas_fonts"
chapters_template = target_dir_template.parent / "chapters.xml"


# def mkv(prog, *args, **kwargs):
#     cmd = [f'mkv{prog}', *args]
#     print("running", cmd)
#     return subprocess.run(cmd, check=True, capture_output=True, text=True, **kwargs)


def mkvidentify(path):
    cmd = ['mkvmerge', "-J", str(path)]
    result = subprocess.run(cmd, check=True, capture_output=True, text=True)
    return json.loads(result.stdout)


def mkvextract(path, *args):
    cmd = ['mkvextract', str(path), *args]
    print("\n[CMD]", cmd)
    return subprocess.run(cmd, check=True, stdout=sys.stdout, stderr=sys.stderr)


def main():
    for ep_num in map(int, sys.argv[1:]):
        src_path = next(src_dir.glob(f"* - {ep_num:02d}*"))
        print("[SRC]", src_path)
        identify = mkvidentify(src_path)

        # extract subs, chapters, attachments
        for track in identify['tracks']:
            if track['codec'] == 'SubStationAlpha':
                subs_id = track['id']
                os.makedirs(str(target_dir_template).format(ep_num=ep_num), exist_ok=True)
                mkvextract(src_path, 'tracks',
                           f"{subs_id}:{str(sub_template).format(ep_num=ep_num)}")
                break
        else:
            print("No subtitle track found")

        font_dir = str(font_dir_template).format(ep_num=ep_num)
        os.makedirs(font_dir, exist_ok=True)
        attach_args = [
            f"{attach['id']}:{str(font_dir_template / attach['file_name']).format(ep_num=ep_num)}"
            for attach in identify['attachments']
        ]
        mkvextract(src_path, 'attachments', *attach_args)

        mkvextract(src_path, 'chapters', str(chapters_template).format(ep_num=ep_num))
        print()


if __name__ == '__main__':
    sys.exit(main())
