#!/usr/bin/env python3 -W ignore::DeprecationWarning
# -*- coding:utf8 -*-
import sys
import traceback
sys.path.append('../')
from util.sentence import *
from util.parse_json import *
from ask_func.generate_question import *
from ask_func.rank import *
from answer_func.answer_question import *
from ask_func.rank_questions import *

def question_type(question):
    question = question.lower()
    question_types = ["where", "when", "who", "what", "how", "which"]
    yn_types = ['cannot','is', 'are', 'were', 'was', 'am', 'can', 'could', \
                'must', 'may', 'will', 'would', 'have', 'had', 'has', 'do', 'did', 'does']
    question_index = []
    q_word = question.split(' ')[0]
    if q_word not in question_types:
        if q_word in yn_types:
            return "yn"
        else:
            return "unknow"
    else:
        for q_type in question_types:
            if question.find(q_type) < 0:
                question_index.append(len(question))
            else:
                question_index.append(question.find(q_type))
        question_type = question_types[question_index.index(min(question_index))]
        # print(question_type)
        return question_type

def main():
    article_file = sys.argv[1]
    questions_file = sys.argv[2]
    questions = read_questions(questions_file)
    paragraphs = open_txt(article_file)
    sentences = tokenize_sentence(paragraphs)

    aList = []
    tList = []
    for k in range(len(questions)):
        question = questions[k]
        q_type = question_type(question)
        answer = None

        try:
            answer = answer_short(sentences, question)
            if answer != None:
                tList.append(answer)
                aList.append(answer)
                continue
        except:
            pass

        try:
            answer = score_short(sentences, question)
        except:
            pass

        if answer == None:
            aList.append("No answer")
            continue

        target = answer
        tList.append(answer)
        if q_type == "yn":
            try:
                answer = answer_YN(answer, question)
            except:
                pass
        elif q_type == "what":
            try:
                answer = answer_what(answer, question)
            except:
                pass
        elif q_type == "how":
            try:
                answer = answer_how(answer, question)
            except:
                pass
        elif q_type == "unknow":
            pass
        else:
            try:
                answer = answer_when(answer, question)
            except:
                pass
        
        if answer == '' or answer == None:
            answer = target
        try:
            aList.append(format_answer(answer))
        except:
            aList.append(answer)
    
    for i in range(len(questions)):
        # print(questions[i])
        # print(tList[i])
        print(aList[i])

if __name__ == "__main__":
    main()