#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Céline Noirot & Pierre MARTIN
# MIAT - INRAe (Toulouse)
# 2021


try:
    import csv
    import subprocess
    import re
    import sys
    import argparse

except ImportError as error:
    print(error)
    exit(1)


# __main__
def main():

    # Manage parameters
    parser = argparse.ArgumentParser(description = \
    'Script which check proccesses launch thanks to the provided options.')
    parser.add_argument('-f', '--file', required = True, default="hifi_steps_command.tsv", help = \
    'Expected processes.')
    args = parser.parse_args()
    
    read_tsv = csv.reader(open(args.file), delimiter='\t')
    header = read_tsv.__next__()
    for cmds in read_tsv: 
        execution_dir=cmds[1]
        # parse expected process
        processes_expected = set()
        for i,val in enumerate(cmds):
            if val=="1" : # this process is expected
                processes_expected.add(header[i])

        # get executed process
        # print("cd "+execution_dir+"; nextflow log $(nextflow log -q | tail -1) -f name,status")
        process = subprocess.Popen("cd "+execution_dir+"; nextflow log $(nextflow log -q | tail -1) -f name,status", stdout = subprocess.PIPE, shell = True, executable = '/bin/bash')
        res, error = process.communicate()
        processes_executed = set()
        for line in res.decode('ascii').split("\n"):
            if line != "":
                process_sample,status = re.split("\t",line)
                cut = re.split(" ",process_sample)
                if len(cut) == 2:
                    process = cut[0]
                    sample = cut[1]
                else:
                    process = process_sample
                if status == "CACHED" or status == "COMPLETED":
                    processes_executed.add(process)

        diff = processes_expected.symmetric_difference(processes_executed)
        if len(diff) != 0 : 
            print ("#### Project:"+ execution_dir + ". Error in following processes: \n-" + "\n-".join(sorted(diff)))
        if len(diff) == 0 :
            print ("#### Project:"+ execution_dir + ". All processes exectuted correctly")


if __name__ == "__main__":
    main()