# Path: augur/io.py
# @contextmanager
# def open_file(path_or_buffer, mode="r", **kwargs):
#     """Opens a given file path and returns the handle.
# 
#     Transparently handles compressed inputs and outputs.
# 
#     Parameters
#     ----------
#     path_or_buffer : str or Path-like or IO buffer
#         Name of the file to open or an existing IO buffer
# 
#     mode : str
#         Mode to open file (read or write)
# 
#     Returns
#     -------
#     IO
#         File handle object
# 
#     """
#     try:
#         with xopen(path_or_buffer, mode, **kwargs) as handle:
#             yield handle
#     except TypeError:
#         yield path_or_buffer
# 
# def read_sequences(*paths, format="fasta"):
#     """Read sequences from one or more paths.
# 
#     Automatically infer compression mode (e.g., gzip, etc.) and return a stream
#     of sequence records in the requested format (e.g., "fasta", "genbank", etc.).
# 
#     Parameters
#     ----------
#     paths : list of str or Path-like objects
#         One or more paths to sequence files of any type supported by BioPython.
# 
#     format : str
#         Format of input sequences matching any of those supported by BioPython
#         (e.g., "fasta", "genbank", etc.).
# 
#     Yields
#     ------
#     Bio.SeqRecord.SeqRecord
#         Sequence record from the given path(s).
# 
#     """
#     for path in paths:
#         # Open the given path as a handle, inferring the file's compression.
#         # This way we can pass a handle to BioPython's SeqIO interface
#         # regardless of the compression mode.
#         with open_file(path) as handle:
#             sequences = Bio.SeqIO.parse(handle, format)
# 
#             for sequence in sequences:
#                 yield sequence
# 
# Path: augur/utils.py
# def is_vcf(filename):
#     """Convenience method to check if a file is a vcf file.
# 
#     >>> is_vcf(None)
#     False
#     >>> is_vcf("./foo")
#     False
#     >>> is_vcf("./foo.vcf")
#     True
#     >>> is_vcf("./foo.vcf.GZ")
#     True
#     """
#     return bool(filename) and any(filename.lower().endswith(x) for x in ('.vcf', '.vcf.gz'))
# 
# def read_vcf(filename):
#     if filename.lower().endswith(".gz"):
#         import gzip
#         file = gzip.open(filename, mode="rt", encoding='utf-8')
#     else:
#         file = open(filename, encoding='utf-8')
# 
#     chrom_line = next(line for line in file if line.startswith("#C"))
#     file.close()
#     headers = chrom_line.strip().split("\t")
#     sequences = headers[headers.index("FORMAT") + 1:]
# 
#     # because we need 'seqs to remove' for VCF
#     return sequences, sequences.copy()


from Bio import SeqIO
from itertools import combinations
from .io import open_file, read_sequences
from .utils import is_vcf, read_vcf
import Bio.Seq
import Bio.SeqRecord
import sys
import csv



def register_arguments(parser):
    parser.add_argument('--sequences', '-s', required=True, help="sequences in FASTA or VCF formats. Augur will summarize the content of FASTA sequences and only report the names of strains found in a given VCF.")
    parser.add_argument('--output', '-o', help="tab-delimited file containing the number of bases per sequence in the given file. Output columns include strain, length, and counts for A, C, G, T, N, other valid IUPAC characters, ambiguous characters ('?' and '-'), and other invalid characters.", required=True)
    parser.add_argument('--verbose', '-v', action="store_true", help="print index statistics to stdout")


def index_vcf(vcf_path, index_path):
    """Create an index with a list of strain names from a given VCF. We do not
    calculate any statistics for VCFs.

    Parameters
    ----------
    vcf_path : str or Path-like
        path to a VCF file to index.
    index_path : str or Path-like
        path to a tab-delimited file containing the composition details for each
        sequence in the given input file.

    Returns
    -------
    int :
        number of strains indexed

    """
    strains, _ = read_vcf(vcf_path)
    num_of_seqs = 0


# Path: augur/io.py
# @contextmanager
# def open_file(path_or_buffer, mode="r", **kwargs):
#     """Opens a given file path and returns the handle.
# 
#     Transparently handles compressed inputs and outputs.
# 
#     Parameters
#     ----------
#     path_or_buffer : str or Path-like or IO buffer
#         Name of the file to open or an existing IO buffer
# 
#     mode : str
#         Mode to open file (read or write)
# 
#     Returns
#     -------
#     IO
#         File handle object
# 
#     """
#     try:
#         with xopen(path_or_buffer, mode, **kwargs) as handle:
#             yield handle
#     except TypeError:
#         yield path_or_buffer
# 
# def read_sequences(*paths, format="fasta"):
#     """Read sequences from one or more paths.
# 
#     Automatically infer compression mode (e.g., gzip, etc.) and return a stream
#     of sequence records in the requested format (e.g., "fasta", "genbank", etc.).
# 
#     Parameters
#     ----------
#     paths : list of str or Path-like objects
#         One or more paths to sequence files of any type supported by BioPython.
# 
#     format : str
#         Format of input sequences matching any of those supported by BioPython
#         (e.g., "fasta", "genbank", etc.).
# 
#     Yields
#     ------
#     Bio.SeqRecord.SeqRecord
#         Sequence record from the given path(s).
# 
#     """
#     for path in paths:
#         # Open the given path as a handle, inferring the file's compression.
#         # This way we can pass a handle to BioPython's SeqIO interface
#         # regardless of the compression mode.
#         with open_file(path) as handle:
#             sequences = Bio.SeqIO.parse(handle, format)
# 
#             for sequence in sequences:
#                 yield sequence
# 
# Path: augur/utils.py
# def is_vcf(filename):
#     """Convenience method to check if a file is a vcf file.
# 
#     >>> is_vcf(None)
#     False
#     >>> is_vcf("./foo")
#     False
#     >>> is_vcf("./foo.vcf")
#     True
#     >>> is_vcf("./foo.vcf.GZ")
#     True
#     """
#     return bool(filename) and any(filename.lower().endswith(x) for x in ('.vcf', '.vcf.gz'))
# 
# def read_vcf(filename):
#     if filename.lower().endswith(".gz"):
#         import gzip
#         file = gzip.open(filename, mode="rt", encoding='utf-8')
#     else:
#         file = open(filename, encoding='utf-8')
# 
#     chrom_line = next(line for line in file if line.startswith("#C"))
#     file.close()
#     headers = chrom_line.strip().split("\t")
#     sequences = headers[headers.index("FORMAT") + 1:]
# 
#     # because we need 'seqs to remove' for VCF
#     return sequences, sequences.copy()


# Path: augur/index.py
from Bio import SeqIO
from itertools import combinations
from .io import open_file, read_sequences
from .utils import is_vcf, read_vcf
import Bio.Seq
import Bio.SeqRecord
import sys
import csv




def register_arguments(parser):
    parser.add_argument('--sequences', '-s', required=True, help="sequences in FASTA or VCF formats. Augur will summarize the content of FASTA sequences and only report the names of strains found in a given VCF.")
    parser.add_argument('--output', '-o', help="tab-delimited file containing the number of bases per sequence in the given file. Output columns include strain, length, and counts for A, C, G, T, N, other valid IUPAC characters, ambiguous characters ('?' and '-'), and other invalid characters.", required=True)
    parser.add_argument('--verbose', '-v', action="store_true", help="print index statistics to stdout")


def index_vcf(vcf_path, index_path):
    """Create an index with a list of strain names from a given VCF. We do not
    calculate any statistics for VCFs.

    Parameters
    ----------
    vcf_path : str or Path-like
        path to a VCF file to index.
    index_path : str or Path-like
        path to a tab-delimited file containing the composition details for each
        sequence in the given input file.

    Returns
    -------
    int :
        number of strains indexed

    """
    strains, _ = read_vcf(vcf_path)
    num_of_seqs = 0


    with open_file(index_path, 'wt') as out_file: