#!/usr/bin/env python3
"""
######################################################################
#
# $HeadURL: https://bss-srv4.bioinformatics.ic.ac.uk/svn/BugBuilder/trunk/bin/run_sis $
# $Author: jamesa $
# $Revision: 179 $
# $Date: 2016-03-10 10:32:17 +0000 (Thu, 10 Mar 2016) $
#
# Wrapper for ragout to permit use via BugBuilder scaffolding stages
#
# This file is part of BugBuilder (https://github.com/jamesabbott/BugBuilder)
# and is distributed under the Artistic License 2.0 - see accompanying LICENSE
# file for details
#
######################################################################

Wrapper for SIS scaffolder to permit use withing BugBuilder's scaffolding configuration.
SIS makes use of MUMmer to carry out alignments, and post-processes the show_coords output.
These MUMmer stages need running prior to executing SIS itself. Following SIS execution the
generated scaffolds (which consist of ordered contigs, with one scaffold per fasta file)
are reprocessed into a multifasta file of 'N' gapped scaffold sequences.


"""
import glob
import subprocess
import sys
import os
from .shared_methods import make_nucmer_delta_show_cmds
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord


def make_ragout_recipe(references, target):
    """ dictates whick files are your references, etc
    should look something like this:

    .references = rf122,col,jkd,n315
    .target = usa

    col.fasta = references/COL.fasta
    jkd.fasta = references/JKD6008.fasta
    rf122.fasta = references/RF122.fasta
    n315.fasta = references/N315.fasta
    usa.fasta = usa300_contigs.fasta

    """
    raw_ref_names = [os.path.basename(x) for x in references]
    # ragout ddoesnt like periods in names
    ref_names = [os.path.splitext(x)[0].replace(".", "_") for x in raw_ref_names]
    ref_names_exts = [os.path.splitext(x)[1] for x in raw_ref_names]
    target_name = os.path.splitext(os.path.basename(target))[0].replace(".", "_")
    lines = [
        "# ragout recipe file generated by BugBuilder",
        ".references = " + ",".join([os.path.splitext(x)[0] for x in ref_names]),
        ".target = " + target_name]
    lines.append(target_name + os.path.splitext(target)[1] + " = " + target)
    for idx, ref in enumerate(references):
        lines.append(ref_names[idx] + ref_names_exts[idx] + " = " + ref)
    return lines


def make_ragout_cmd(exe, scaff_dir, threads, ragout_recipe):
    return "{exe} --outdir {scaff_dir} --synteny sibelia --threads {threads} {ragout_recipe} --debug".format(**locals())


def run(config, args, results, ref, contigs, scaff_dir, logger):
    """ we need to explicitly set the reference and the contigs files cause we
    may have partitioned them (using blast to see which contigs go with
    which contigs)
    """
    if config.python2 is None:
        raise ValueError(
            "ragout requires having python2 available! "+
            " we recommend creaing a conda environement just for " +
            " ragout (`conda create --name ragout ragout`) which " +
            " ensures that ragout and its dependencies will be installed" +
            " and available in the path with python2")
    recipe_file = os.path.join(scaff_dir, "ragout_recipe.txt")
    recipe_lines = make_ragout_recipe(references=args.references, target=contigs)
    with open(recipe_file, "w") as outf:
        for line in recipe_lines:
            print(line)
            outf.write(line + "\n")

    logger.debug("Using ragout to scaffold %s against %s", contigs,
                 ", ".join(args.references))
    cmd = make_ragout_cmd(exe=config.ragout, scaff_dir=scaff_dir,
                     threads=args.threads, ragout_recipe=recipe_file)
    logger.debug(cmd)
    subprocess.run(cmd,
                   shell=sys.platform != "win32",
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE,
                   check=True)
