#!/usr/bin/python3

import os
import re
import sys

if __name__ == "__main__":
    root = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
    bench = os.path.join(root, "Bench")
    bench_txt = os.path.join(bench, "Text")
    bench_bpf = os.path.join(bench, "BPF")
    bench_out = os.path.join(bench, "Out")

    if not os.path.exists(bench_out):
        os.mkdir(bench_out)

    bpf_ext = "par"
    txt_ext = "txt"
    srt_ext = "srt"
    sbt_ext = "sub"

    bpfs = sorted(os.listdir(bench_bpf))

    print("Version:")
    os.system(os.path.join(root, "subtitle") + " --version")
    print()

    failure = 0

    for i, bpf in enumerate(bpfs):
        print(i + 1, "/", len(bpfs), end="\r")
        stem = re.sub(bpf_ext + "\Z", "", bpf)
        txt = stem + txt_ext

        bpf_path = os.path.join(bench_bpf, bpf)
        txt_path = os.path.join(bench_txt, txt)

        markers = ("punct", "newline")
        if bpf.startswith("tag"):
            markers += ("tag",)

        for marker in markers:
            for outformat in (bpf_ext, srt_ext, sbt_ext):
                outfile = stem + outformat
                
                if not os.path.exists(os.path.join(bench_out, marker)):
                    os.mkdir(os.path.join(bench_out, marker))

                out_path = os.path.join(bench_out, marker, outfile)

                if outformat == "par":
                    outformat = "bpf+trn"

                tiers = ["TRO"]
                if marker == "tag" and outformat != "bpf+trn":
                    tiers.append("ORT")
                    
                for tier in tiers:
                    cmd = " ".join([os.path.join(root, "subtitle"), \
                        "--bpf", bpf_path, "--tier", tier, "--transcription", txt_path, "--outfile", out_path, \
                        "--marker", marker, "--outformat", outformat, "--maxlength 40", "--verbose"])

                    i = os.system(cmd)

                    if i != 0:
                        failure += 1
                        print("Failed:", cmd, file = sys.stderr)

    print()
    print("Output files can be found in Bench/Out/*. You might want to check them.")
    if i != 0:
        print("\nCAUTION: THERE WERE FAILED TESTS!")
    else:
        print("NO FAILED TESTS")

    sys.exit(failure)
