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

"""----------------------------------------------------------------------------
  Script Name: main.py
  Description: Do functional tests on observed results using expected results
  Input files: Expected and observed folders
  Created By:  Pierre Martin
  Date:        2021-12-16
-------------------------------------------------------------------------------
"""

# Metadata
__author__ = 'Pierre Martin \
- MIAT - PF Genotoul'
__copyright__ = 'Copyright (C) 2021 INRAe'
__license__ = 'GNU General Public License'
__version__ = '1'
__email__ = 'support.bioinfo.genotoul@inra.fr'
__status__ = 'dev'

# Usage
    ## cd [work_directory]
    ## python metagwgs/functional_tests/main.py -step [step] -exp_dir ./test_expected_logs -obs_dir ./[work_directory]/results [optional: --script ./[work_directory]/launch_example.sh] [optional: --verbose]

try:
    import sys
    import re
    import os
    from collections import OrderedDict
    # Import functions from functions.py (same directory as main.py)
    from functions import parse_arguments, launch_nextflow, check_files, test_file

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

# Dictionary of steps, ordered with numeric values associated
global steps_list
steps_list = OrderedDict([
    ("01_clean_qc", 1),
    ("02_assembly", 2),
    ("03_filtering", 3),
    ("04_structural_annot", 4),
    ("05_protein_alignment", 5),
    ("06_func_annot", 6),
    ("07_taxo_affi", 7),
    ("08_binning", 8)
])

# Dictionary of test methods to use on files found in exp_dir (with exceptions i.e. cut_diff)
global methods
methods = OrderedDict([
    ("cut_diff", r".*_cutadapt\.log"),
    ("sort_diff", [".krona",".flagstat",".idxstats",".bed",".m8",".clstr",".txt",".summary",".best_hit",".log",".tsv",".csv",".out",".fasta",".fa",".faa",".ffn",".fna",".0123",".gff",".len",".stats",".marker",".noclass",".tooshort",".json"]), #.0123 for .fa.0123
    ("no_header_diff", [".annotations",".seed_orthologs"]),
    ("zdiff", [".gz"]),
    ("not_empty", [".zip",".html",".pdf",".bam",".bai", ".amb",".ann",".bwt",".64",".pac",".sa",".tex",".stdout",".png"])#.64 for .bwt.2bit.64
])

# __main__
def main():

    # Parse arguments
    global args
    args = parse_arguments()

    if args.script:

        # If user gave a script to launch nextflow, launch before doing tests
        launch_nextflow(args.script)

    if args.step not in steps_list:

        # If step doesn't exist (i.e isn't in the list "steps_list"), quit and prompt user with proper steps list
        sys.exit("-step doesn't exist, please chose from: {}".format(steps_list.keys()))

    else:

        # Store final out of each step for end print
        outs = list()

        # Test each step before and equal to user given step
        for step in steps_list:
            
            # Steps are ordered in a dict with a numeric value associated to each key
            if steps_list[step] <= steps_list[args.step]:

                # Launch test on expected and observed files from this step
                out = check_files(args.exp_dir, args.obs_dir, step, methods, args.verbose)
                outs.append(out)

        print(''.join(outs))


if __name__ == "__main__":

    # Launch main script
    main()