import sys
import argparse
import demucs.separate
import subprocess
import shlex
from pathlib import Path
from assUtils import AssWriter, getSyls

from autosyl.segment import segment


parser = argparse.ArgumentParser(description='AutoKara - Automatic karaoke timing tool')
parser.add_argument("source_file", type=str, help="The video/audio file to time")
parser.add_argument("ass_file", type=str, help="The ASS file in which to output the karaoke")
parser.add_argument("--vocals", action="store_true", help="Treat the input as vocals file, i.e. do not perform vocals extraction")
parser.add_argument("--ref", help="Use an ASS file as reference")

args = parser.parse_args()

ass_file = args.ass_file

if not args.vocals :
    print("Extracting audio from video file...")
    Path("./media/audio").mkdir(parents=True, exist_ok=True)
    basename = Path(args.source_file).stem
    audio_file = "media/audio/%s.wav" % basename

    subprocess.call(shlex.split('./extractWav.sh "%s" "%s"' % (args.source_file, audio_file)))

    Path("./media/vocals").mkdir(parents=True, exist_ok=True)
    output_folder = "./media/vocals"

    print("Isolating vocals...")

    # Not working, don't know why
    # demucs.separate.main(shlex.split('--two-stems vocals -o "%s" "%s"' % (output_folder, audio_file)))
    subprocess.call(shlex.split('demucs --two-stems vocals -o "%s" "%s"' % (output_folder, audio_file)))

    vocals_file = "./media/vocals/htdemucs/%s/vocals.wav" % basename
else:
    vocals_file = args.source_file

if args.ref:
    reference_syls = getSyls(args.ref)
else:
    reference_syls = None

print("Identifying syl starts...")
syls = segment(vocals_file, reference_syls=reference_syls)
print(syls)

print("Syls found, writing ASS file...")
writer = AssWriter()
writer.openAss(ass_file)
writer.writeHeader()
writer.writeSyls(syls)
writer.closeAss()