#!/usr/bin/env python
"""Adds orthography in eval file generated by different model."""
import argparse
import collections
import functools
import logging
import multiprocessing
from tqdm import tqdm
import codecs
import random
import re 

def saveToFile(fileName,content):
    f=open(fileName, "a+")
    f.write(content)
    f.close()

# This def reads test corpus and generats a Dict of Othography -> Actual Pronounciation
def loadOrthopgraphy(testCorpus):
    othoDict = {}
    
    with codecs.open(testCorpus, "r", "utf-8")  as fp:
        line = fp.readline()
        while line:
            lineparts = re.split('\t|,',line.rstrip())
            if len(lineparts) >= 2:
                ortho = lineparts[0]
                pronoun = lineparts[1]
                #print('ortho',ortho,'pronoun',pronoun)
                if (pronoun in othoDict.keys()):
                    print('Same pronounciation of 2 different words',pronoun,'|',ortho,'|',othoDict[pronoun])
                else: 
                    othoDict[pronoun] = ortho     	
            line = fp.readline()
    
    return othoDict

# This def reads model output and generats a Dict of ActualOutput -> complete line indicating actual and predicted out
def loadModelOut(testCorpus):
    othoDict = {}
    with codecs.open(testCorpus, "r", "utf-8")  as fp:
        line = fp.readline()
        while line:
            lineparts = re.split('\t|,',line)
            if len(lineparts) >= 2:
                pronoun = lineparts[0]
                if (pronoun in othoDict.keys()):
                    print('Same pronounciation of 2 different words',pronoun,'||',line,'||',othoDict[pronoun])
                else: 
                    othoDict[pronoun] = line
            line = fp.readline()
    return othoDict


def main(args):
    orthoDict = loadOrthopgraphy(args.testCorpous)
    modelOutputDict = loadModelOut(args.modelOutputFile)
    print('Number of items orthoDict',len(orthoDict))
    print('Number of items ModelDict',len(modelOutputDict))


    for actualPron,line in modelOutputDict.items():
        #print(actualPron)
        if actualPron in orthoDict.keys(): 
            ortho = orthoDict[actualPron]
            #print('found',ortho,line.rstrip())
            saveToFile(args.resultOutFile,ortho+'\t'+line)


if __name__ == "__main__":
    logging.basicConfig(format="%(levelname)s: %(message)s")
    parser = argparse.ArgumentParser(description="FileName")
    parser.add_argument(
        "--modelOutputFile", required=True, help="Path to model output file. It should be a tab / comma separated file where first column represent actual production"
    )
    parser.add_argument(
        "--testCorpous", required=True, help="Path to gold standard test corpus. This corpus should be a tab separated file with first column as orthography and second is actual pronounciation"
    )

    parser.add_argument("--resultOutFile", required=True, help="Output file name to append result to")

    main(parser.parse_args())