#!/usr/bin/python3
import numpy as np
import argparse
from pkcm_rust_lib import parse_helices

parser = argparse.ArgumentParser(description="given a PKCM model and an alignment of sequences onto that model, report the score of each aligned sequence by the model.")

parser.add_argument('pkcm_file', type=str, help='.pkcm file containing the PKCM model')
parser.add_argument('alignment', type=str, help='alignment to score (stockholm format)')
parser.add_argument('seed_alignment', type=str, help='.seed seed alignment used to build the pkcm')
parser.add_argument('--meanlength', action='store_true', help="in the NULL model, the length term is computed from the mean\
                    of sequence lengths in the seed, instead of the consensus length.")

args = parser.parse_args()

lengths = []
for line in open(args.seed_alignment).readlines():
    if not line.startswith("#") and line not in ["\n","//\n"]:
        seq = line.split(' ')[-1].rstrip('\n')
        lengths.append(len(seq.replace('-','')))
    if line.startswith('#=GC SS_cons '):
        ss_cons = line.split(' ')[-1].rstrip('\n')
    if line.startswith('#=GC RF'):
        rf_line = line.split(' ')[-1].rstrip('\n')

if args.meanlength:
    p_length = np.mean(lengths) / (np.mean(lengths) + 1)
else:
    ss_cons_length = len(ss_cons.replace('.','').replace('~',''))
    p_length = ss_cons_length / float(ss_cons_length + 1)

for line in open(args.alignment).readlines():
    if line.startswith('#=GC SS_cons '):
        ss_cons = line.split(' ')[-1].rstrip('\n')

helices = parse_helices(args.pkcm_file, False)

outer_lefts = []   # contains the consensus columns that are outer_lefts
inner_lefts = []
inner_rights = []
outer_rights = []

for helix in helices:
    i,j,k,l = helix.get_boundaries()
    outer_lefts.append(i)
    inner_lefts.append(j)
    inner_rights.append(k)
    outer_rights.append(l)

left_intervals = {}
right_intervals = {}



for line in open(args.alignment).readlines():

    if not line.startswith("#") and line not in ["\n","//\n"]:
        aliseq = line.split(' ')[-1].rstrip('\n')
        sequence = aliseq.replace('-','')
        ident = line.split(" ")[0]

        inserts = {}
        cons_cols = {}
        
        curr_insert = ""

        # the first insert
        for k, c in enumerate(list(ss_cons)):
            if c in ['.','~']:
                curr_insert += aliseq[k]
                continue
            break

        inserts[0] = curr_insert        

        cons_col = 1
        for k, c in enumerate(list(ss_cons)):
            if c in ['.','~']:
                curr_insert += aliseq[k]
                continue

            cons_cols[cons_col] = aliseq[k]
            if cons_col > 1:
                inserts[cons_col-1] = curr_insert
            
            curr_insert = ""
            cons_col += 1

        inserts[cons_col-1] = curr_insert

        score = 0.0
        total_emission = 0.0
        total_transition = 0.0

        for helix in helices:
            i,j,k,l = helix.get_boundaries()

            include_outer_left_insert = False
            if i > 1 and i-1 in outer_rights:
                include_outer_left_insert = True
    
            include_inner_left_insert = False
            if j+1 in outer_lefts:
                include_inner_left_insert = True

            include_inner_right_insert = True # always
            
            include_outer_right_insert = False # always except root

            # root case
            if helix.name=="Helix_root":
                include_outer_left_insert = True
                include_inner_left_insert = True
                include_outer_right_insert = True

            left_cons = ""
            right_cons = ""

            if i==j: # empty left half of the root helix
                left_seq = inserts[0]
                left_cons = "."*len(inserts[0])
            if k==l:
                right_seq = inserts[l]
                right_cons = "."*len(inserts[l])
            
            if i!=j:
                left_seq = ""
                if include_outer_left_insert:
                    left_seq += inserts[i-1]
                    left_cons += "."*len(inserts[i-1])
                for col in range(i,j,1):
                    left_seq += cons_cols[col]
                    left_cons += "_"
                    left_seq += inserts[col]    
                    left_cons += "."*len(inserts[col])
                left_seq += cons_cols[j]
                left_cons += "_"
                if include_inner_left_insert:
                    left_seq += inserts[j]    
                    left_cons += "."*len(inserts[j])

            if k!=l:
                right_seq = ""
                if include_inner_right_insert:
                    right_seq += inserts[k-1]
                    right_cons += "."*len(inserts[k-1])
                for col in range(k,l,1):
                    right_seq += cons_cols[col]
                    right_cons += "_"
                    right_seq += "."*len(inserts[col])
                    right_cons += "."*len(inserts[col])
                right_seq += cons_cols[l]
                right_cons += "_"
                if include_outer_right_insert:
                    right_seq += inserts[l]
                    right_seq += "."*len(inserts[l])

            #print("helix name", helix.name)
            #print(repr(left_seq))
            #print(repr(left_cons))
            #print(repr(right_seq))
            #print(repr(right_cons))
            score_inc, emission_part, transition_part, state_list = helix.score_aligned_seq(left_seq, left_cons, right_seq, right_cons)
            total_emission += emission_part
            total_transition += transition_part
            #print(state_list)
            #print(score_inc)
            score += score_inc 

        L = len(sequence)
        correction = 2*L-(L-1)*np.log2(p_length)-np.log2(1-p_length)
        print(ident, score,f"(emission : {total_emission}, transition: {total_transition})","+", correction,"=", score+correction)


