#!/usr/bin/env python3

# core
import argparse
import logging
import os

# local
from cathpy.core.align import Align

parser = argparse.ArgumentParser(
    description="Update the scorecons data for a STOCKHOLM alignment",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('--in', '-i', type=str, required=True, dest='in_file',
                    help='input alignment file')

parser.add_argument('--out', '-o', type=str, dest='out_file', required=False,
                    help='output STOCKHOLM alignment file')

parser.add_argument('--format', '-f', type=str, required=True, default='sto', choices=['sto', 'fasta'],
                    help='alignment format of input file')

parser.add_argument('--replace', action='store_true', default=False,
                    help='overwrite the input alignment file with updated scorecons')

parser.add_argument('--verbose', '-v', required=False, action='count', default=0,
                    help='more verbose logging')

parser.add_argument('--quiet', '-q', required=False, default=0,
                    help='less versbose logging')

if __name__ == '__main__':
    args = parser.parse_args()

    log_level = logging.DEBUG if args.verbose > 0 else logging.INFO
    if args.quiet:
        log_level = logging.WARN
    logging.basicConfig(
        level=log_level, format="%(message)s")

    if args.format == 'sto':
        aln = Align.from_stockholm(args.in_file)
    elif args.format == 'fasta':
        aln = Align.from_fasta(args.in_file)

    if args.replace and args.format == 'fasta':
        raise Exception(
            'cannot use --replace when input format is fasta (nothing will have changed)')

    old_dops_score = aln.dops_score
    old_scorecons = aln.meta['scorecons'] if 'scorecons' in aln.meta else '-'

    aln.add_scorecons()

    print('{:70s} {:.3f}'.format(args.in_file, aln.dops_score))

    logging.debug('OLD_DOPS:      %s', old_dops_score)
    logging.debug('NEW_DOPS:      %s', aln.dops_score)

    if args.out_file:
        logging.info("Writing new alignment file: %s", args.out_file)
        aln.write_sto(args.out_file)

    if args.replace:
        logging.info("Replacing alignment file: %s", args.in_file)
        aln.write_sto(args.in_file)

    logging.debug('DONE')
