""" `indexGVF`  """
from __future__ import annotations
import argparse
from pathlib import Path
import tempfile
from moPepGen import get_logger, check_sha512
from moPepGen.seqvar import GVFIndex
from moPepGen.seqvar import GVFMetadata
from moPepGen.cli import common


INPUT_FILE_FORMATS = ['.gvf']

# pylint: disable=W0212
def add_subparser_index_gvf(subparsers:argparse._SubParsersAction):
    """ CLI for moPepGen indexGVF """
    p:argparse.ArgumentParser = subparsers.add_parser(
        name='indexGVF',
        help='Generate index for GVF file.',
        description='Generate index for GVF file.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    common.add_args_input_path(
        parser=p, formats=INPUT_FILE_FORMATS,
        message='File path to GVF file. Must be generated by any of the'
        ' moPepGen parsers。'
    )
    common.add_args_debug_level(p)
    p.set_defaults(func=index_gvf)
    common.print_help_if_missing_args(p)
    return p


def index_gvf(args:argparse.Namespace):
    """ Generate GVF index """
    input_file:Path = args.input_path
    common.validate_file_format(input_file, INPUT_FILE_FORMATS, True)
    output_file = input_file.with_suffix(input_file.suffix + '.idx')
    with open(input_file, 'rb') as handle:
        sum_val = check_sha512(handle)

    common.print_start_message(args)

    with open(input_file, 'rt') as handle:
        metadata = GVFMetadata.parse(handle)

    is_circ_rna = metadata.is_circ_rna()

    with open(input_file, 'rb') as in_handle:
        with tempfile.TemporaryFile(mode='w+t') as temp_file:
            temp_file.write(f"# CHECKSUM={sum_val}\n")
            in_handle.seek(0)
            it = GVFIndex.iterate_pointer(handle=in_handle, is_circ_rna=is_circ_rna)
            for pointer in it:
                temp_file.write(pointer.to_line() + '\n')
            temp_file.seek(0)
            with open(output_file, 'wt') as out_handle:
                for line in temp_file:
                    out_handle.write(line)

    get_logger().info('GVF index generated.')
