#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 16:02:49 2021

@author: GIRAUD Delphine


"""
import sys
# Automatic classification RIX

# Input files:
#     argv[1] : *_chr_allTEs_nr_noSSR_join_path.annotStatsPerTE.tab Standard Output REPET TEannot Step 7
#     argv[2] : *_Profiles.gff3 Standard Output REPET CreateGFF3sForClassifFeatures.py (script included in  REPET package)
#     argv[3] : results_autoClassRLX.txt corresponded to standard output Additional file 2


# Output file:
#     result_autoClassRLX_autoClassRIX.txt corresponded to argv[1] file with additionnal informations for manual curation



listOtherKnown = ["TREP", "OSLINE", "L1", "ATLINE", "profiles", "LINE", "Dl_Skipper", "ATGP", "TONT", "GYPOT", "TY3-", "TIRANT", "POPCOP", "M2_VM", "LTR-", "GYVIT", "CASTOR", "SZ", "SHACOP", "RLG", "RETROFIT", "POPGY", "GYRAV", "GYPSHAN", "COP", "ATHILA", "ATCOPIA", "TermRepeats", "GmCOPIA", "non-termLTR", "Gypsy", "Copia", "other", "termLTR", "termTIR", "SSR", "TElength", "TE_BLRx", "<", ">", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ]
listeLINEKnown = ["PF13456.6_RVT", "PF13966.6_zf-RVT", "PF00078.27_RVT", "PF14111.6_DUF4283", "PF14392.6_zf-CCHC", "PF03372.23_Exo", "PF14529.6_Exo"]

dicoFull = {}


file1 = open(sys.argv[1], "r")
for line in file1:
    if not line.startswith("Seq_name"):
        name = line.split("\t")[0]
        length = int(line.split("\t")[1])
        Wcode = line.split("\t")[11]
        
        listOther = []
        dicoAN = {}
        if Wcode == "RIX":
            coding = line.split("\t")[13]
            if "profiles" in coding:
                coding = coding.split("profiles: ")[1]
                coding = coding.split(" ")
                for ele in coding :
                    if ele.startswith("PF"):
                        ele = ele.split("_")[0] + "_" + ele.split("_")[1]
                        if ele not in listOtherKnown:
                            dec = False
                            for truc in listOtherKnown:
                                if ele.startswith(truc):
                                    dec = True
                                    break
                            
                            if dec == False:
                                listOther.append(ele)
                    else:
                        dec = False
                        for truc in listOtherKnown:
                            if ele.startswith(truc):
                                dec = True
                                break
                        
                        if dec == False:
                            listOther.append(ele)
                        

            other = line.split("\t")[15]
            if other != "other=(NA)":
                other = other.split(" ")
                for ele in other:
                    dec = False
                    for ele2 in listOtherKnown:
                        if ele.startswith(ele2):
                            dec = True
                            break
                    
                    if dec == False:
                        listOther.append(ele)                            

            struc = line.split("\t")[14]
            listStruc = [False, False, False]
            if "polyAtail" in struc:
                listStruc[0] = True
            if "SSR" in struc:
                if "start" in struc:
                    listStruc[1] = True
                elif "end" in struc:
                    listStruc[2] = True
        
        
            dicoFull[name] = [length, listOther, listStruc]
            
file1.close()

dico_clean = {}
for FLF in dicoFull.keys():
    listPos = []
    for i in range(0, dicoFull[FLF][0]+1):
            listPos.append(0)

    listDomPF = dicoFull[FLF][1]
    RVT = False

    fileProfile = open(sys.argv[2], "r")

    for line in fileProfile:
        if not line.startswith("#"):
            cons = line.split("\t")[0]
            if cons == FLF:
                line = line.replace("\n", "")
                types = line.split("\t")[2]
                if types == "exon":
                    evalue = line.split("\t")[5]
                    evalue = evalue.replace(',', '.')
                    evalue = float(evalue)
                    
                    if evalue < 0.01:
                        start = int(line.split("\t")[3])
                        end = int(line.split("\t")[4])
                        des = line.split("\t")[8]
                        des = des.split(";")
                        for ele in des:
                            if ele.startswith("Target="):
                                des = ele
                                break
                        des = des.split(" ")[0]
                        des = des.replace("Target=", "")
                        if des.startswith("PF"):
                            PF = des.split("_")[0] + "_" + des.split("_")[1]
                            if PF in listeLINEKnown:
                                for i in range(start, end+1):
                                    listPos[i] = PF
                            else:
                                if PF not in listDomPF:
                                    listDomPF.append(PF)
                        else:
                            if des.startswith("GyDB"):
                                des = des.split("_")[1] +"_"+des.split("_")[2]
                                if des not in listDomPF:
                                    listDomPF.append(des)
                                
                            else:
                                print("Add dest\t" + des)
                                
    fileProfile.close()
    
    
    pattern = ""
    start = 0
    end = 0
    for i in range(0, dicoFull[FLF][0]+1):
        curDom = listPos[i]
        if curDom != 0:
            curDom = curDom.upper()
            if not pattern.endswith(curDom):
                if pattern == "":
                    start = i
                    pattern = curDom
                else:
                    pattern = pattern + "-" + curDom
            else:
                end = i
    pattern = str(start) + "-" + pattern + "-" + str(end)
    if pattern == "0--0":
        pattern = ""
    
    list_struc = dicoFull[FLF][2]
    outString = "\tRIX\tAUTO\t"
    
    if "RVT" in pattern :
        if True in list_struc:
            outString = outString + "keep\tOK: " + pattern
        else:
            outString = outString + "\t" + pattern
    else:
        outString = outString + "\t" + pattern
        
    
    listKnown = []
    listNew = []
    for dom in listDomPF:
        if dom in listeLINEKnown :
            listKnown.append(dom)
        else:
            listNew.append(dom)

    if listDomPF != []:
        if listKnown != [] and listNew != []:
            outString = outString + ";" + "NewDomaine:"+ str(listNew) + ";" + "KnownDomaine:"+ str(listKnown)
        elif listKnown == [] and listNew != []:
            outString = outString + ";" + "NewDomaine:"+ str(listNew)
        elif listKnown != [] and listNew == []:
            outString = outString + ";" + "KnownDomaine:"+ str(listKnown)
            
    dico_clean[FLF] = outString


file3 = open(sys.argv[3], "r")

file1_clean = open("result_autoClassRLX_autoClassRIX.txt", "w")
file1_clean.write("Seq_name\tlength\tcovg\tclusMCL\tfrags\tfullLgthFrags\tcopies\tfullLgthCopies\tmeanId\tconfused\tWcode_old\tWcode\tnew-classif\tqui\tdecision\tcommentaire\tcovSSR%\tcoding\tstruc\tother\tresB_LTRStruc(nbMatch;bestHit;%id,len;eval)\tresB_SINE_Finder(nbMatch;bestHit;%id,len;eval)\n")

for line in file1:
    if not line.startswith("Seq_name"):
        cons = line.split("\t")[0]
        if cons in dico_clean.keys():
            list_start = line.split("\t")[0:12]
            list_end = line.split("\t")[16:]
            outString2 = ""
            for ele in list_start:
                if outString2 == "":
                    outString2 = ele
                else:
                    outString2 = outString2 + "\t" + ele

            outString2 = outString2 + dico_clean[cons]
    
            for ele in list_end:
                outString2 = outString2 + "\t" + ele
            
            
            file1_clean.write(outString2)            
        
        
        else:
            file1_clean.write(line)
    
file3.close()
file1_clean.close()
