#!/usr/bin/env python3
"""
For each file in search result dir, create a config pointing to it
"""

import os
import sys
import yaml

from copy import deepcopy

SEARCH_RESULT_DIR = r"/path/to/search_results"
REPORT_KEY = "mpa_report"
FASTAS = [r"/path/to/fasta.fasta", ]
RESULT_BASE_DIR = r"/path/to/output"
TEMPLATE_JOB_CFG = r"/path/to/config_template.yaml"


def main():
    global FASTAS
    for f in [SEARCH_RESULT_DIR, *FASTAS, TEMPLATE_JOB_CFG]:
        if not os.path.exists(f):
            print(f"specified file does not exist: {f}", file=sys.stderr)
            sys.exit(1)
    FASTAS = [os.path.abspath(f) for f in FASTAS]

    if not os.access(RESULT_BASE_DIR, os.W_OK | os.X_OK):
        print(f"Permission error: Cannot write to specified output directory {RESULT_BASE_DIR}", file=sys.stderr)
        sys.exit(1)

    (_, _, search_results) = next(os.walk(SEARCH_RESULT_DIR))
    allowed_extensions = [".txt", ".tsv", ".csv", ".xls"]

    search_results = [f for f in search_results if os.path.splitext(f)[1] in allowed_extensions]
    if len(search_results) == 0:
        print(f"No file(s) with valid extension ({allowed_extensions}) found in\n"
              f"\t{SEARCH_RESULT_DIR}",
              file=sys.stderr)
        sys.exit(1)
    print(f"Will create dedicated config files in {RESULT_BASE_DIR}\n"
          f"for file found in {RESULT_BASE_DIR}\n"
          "\t" + "\n\t".join(search_results),
          file=sys.stderr)

    with open(TEMPLATE_JOB_CFG, "rt") as f:
        template_cfg = yaml.safe_load(f)

    if "fastas" not in template_cfg["input"]:
        print(f"missing fastas subsection in input section of {TEMPLATE_JOB_CFG}", file=sys.stderr)
        sys.exit(1)

    template_cfg["input"]["fastas"] = FASTAS

    lst_cfgs = []
    for s_res in search_results:
        cfg = deepcopy(template_cfg)
        cfg["general"]["job_name"] = s_res

        # construct full path to s_res
        s_res_full_path = os.path.join(SEARCH_RESULT_DIR, s_res)
        cfg["input"][REPORT_KEY] = s_res_full_path

        s_res_basename_wo_ext = os.path.splitext(os.path.basename(s_res))[0]
        out_base_dir_i = os.path.join(RESULT_BASE_DIR, s_res_basename_wo_ext)
        input_subdir = os.path.join(out_base_dir_i, "input")
        cfg["output_dir"] = out_base_dir_i
        out_cfg_path = os.path.join(input_subdir, "config.yaml")

        if os.path.exists(out_cfg_path):
            print(f"Error: Target config file already exists: {out_cfg_path}", file=sys.stderr)
            sys.exit(1)

        os.mkdir(out_base_dir_i)
        os.mkdir(input_subdir)
        with open(out_cfg_path, 'w') as handle:
            yaml.dump(cfg, handle, default_flow_style=False)

        lst_cfgs.append(out_cfg_path)

    if not len(lst_cfgs) == len(set(lst_cfgs)):
        print(f"basenames of search results must be unique!",
              file=sys.stderr)
        sys.exit(1)

    print("Written config files:\n" +
          "\n".join(lst_cfgs),
          file=sys.stderr)
    sys.exit(0)


if __name__ == "__main__":
    main()
