#!/usr/bin/env python

"""
Remove ref blocks
"""

import logging

import click
import hail as hl

from joint_calling.utils import get_validation_callback, file_exists
from joint_calling import utils, _version

logger = logging.getLogger('joint-calling')
logger.setLevel('INFO')


@click.command()
@click.version_option(_version.__version__)
@click.option(
    '--mt',
    'mt_path',
    required=True,
    callback=get_validation_callback(ext='mt', must_exist=True),
    help='path to the raw sparse Matrix Table generated by combine_gvcfs.py',
)
@click.option(
    '--out-mt',
    'out_mt_path',
    required=True,
    callback=get_validation_callback(ext='mt', must_exist=False),
    help='path to write the final annotated soft-filtered Matrix Table',
)
@click.option(
    '--local-tmp-dir',
    'local_tmp_dir',
    help='local directory for temporary files and Hail logs (must be local).',
)
@click.option(
    '--overwrite/--reuse',
    'overwrite',
    is_flag=True,
    help='if an intermediate or a final file exists, skip running the code '
    'that generates it.',
)
@click.option(
    '--hail-billing',
    'hail_billing',
    help='Hail billing account ID.',
)
def main(
    mt_path: str,
    out_mt_path: str,
    local_tmp_dir: str,
    overwrite: bool,  # pylint: disable=unused-argument
    hail_billing: str,  # pylint: disable=unused-argument
):  # pylint: disable=missing-function-docstring
    utils.init_hail('make_noref_mt', local_tmp_dir)

    if file_exists(out_mt_path):
        if overwrite:
            logger.info(f'Output {out_mt_path} exists and will be overwritten')
        else:
            logger.error(
                f'Output file {out_mt_path} exists, use --overwrite to overwrite'
            )
            return
    
    mt = hl.read_matrix_table(mt_path)
    
    # hl.len(mt.alleles) > 1 - find sites with an ALT allele
    # hl.agg.any(mt.GT.is_non_ref() - check that there is any sample with non-ref
    #    genotype present, in case if all samples with ALT were filtered out
    mt = mt.filter_rows((hl.len(mt.alleles) > 1) & hl.agg.any(mt.GT.is_non_ref()))
    mt.write(out_mt_path, overwrite=True)


if __name__ == '__main__':
    main()  # pylint: disable=E1120
