#!/usr/bin/env python
import argparse

import immunedb.common.config as config
from immunedb.aggregation.clones import ClonalWorker, run_clones


def add_defaults(parser):
    parser.add_argument('--subject-ids', nargs='+', type=int,
                        help='Limit generation to certain subjects')
    parser.add_argument('--level', default='aa', choices=['aa', 'nt'], help='''
        The level at which to compare similarity, either amino-acids or
        nucleotides''')
    parser.add_argument('--min-similarity', type=float, default=.85,
                        help='''Minimum similarity allowed between sequence
                        CDR3 within a clone''')
    parser.add_argument('--reduce-difference', type=int, default=0,
                        help='''Collapses clones with this many different
                        nucleotides in the CDR3, regardless of gene calls''')
    parser.add_argument('--min-copy', type=int,
                        default=ClonalWorker.defaults['min_copy'],
                        help='''The minimum copy number that sequences
                        must have in the subject to be included in
                        clones.''')
    parser.add_argument('--max-padding', type=int,
                        default=ClonalWorker.defaults['max_padding'],
                        help='''Maximum V-padding a sequence may have to
                        be added to a clone.''')
    parser.add_argument('--skip-regen', action='store_true',
                        help='''If specified all clones (limited by
                        subject if --subject is specified) will be KEPT
                        before creating new clones.''')
    parser.add_argument('--gene', default=None,
                        help='''If specified, only sequences of the given gene
                        type will be assigned clones.  Useful if you have
                        BCR and TCR sequences within a single subject.''')


if __name__ == '__main__':
    main_parser = config.get_base_arg_parser('Clusters sequences into clones')
    subparsers = main_parser.add_subparsers(
        dest='method',
        help='''The method to use for clonal inference''')

    # Similarity
    parser = subparsers.add_parser(
        'similarity',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help='''Constructs clones based on CDR3 amino-acid hamming distance''')
    add_defaults(parser)

    # Clustering
    parser = subparsers.add_parser(
        'cluster',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        help='''Constructs clones based on hierarchical clustering''')
    add_defaults(parser)

    args = main_parser.parse_args()
    session = config.init_db(args.db_config)

    run_clones(session, args)
