#/usr/bin/env python
# -*- coding:utf-8 -*-

from snownlp import SnowNLP
import sys
import json

import build

data_loc = '../data/'

def read_dict(input_str):
    dict_file = open(data_loc+'probabilities.dict.json', 'r')
    json_probs = dict_file.read()
    probabilities = json.loads(json_probs)
    dict_file.close()

    token_probs = {}
    tokens = []
    tokens = SnowNLP(input_str).words
#    tokens = input_str.split()
#    tokens = SnowNLP(input_str)
    for token in tokens:
        token = token.lower()
        if token in probabilities:
            token_probs[token] = probabilities[token]
        else:
            token_probs[token] = 0.4
    return token_probs


def calculate(token_probs, danger_size):
    #general sort function
    def sort_func(x):
        return abs(token_probs[x] - 0.5)

    danger_tokens = []
    for token in sorted(token_probs, key=sort_func, reverse=True):
        danger_tokens.append(token_probs[token])
        if len(danger_tokens) == danger_size:
            break

    p_a = 1
    p_b = 1
    for token in danger_tokens:
        p_a = p_a * token
        p_b = p_b * (1-token)
        if p_a + p_b == 0:
            sys.exit()

    spam_probability = p_a / (p_a + p_b)
    return spam_probability


def main():
    # 1. calculation 2. build the hash
    from optparse import OptionParser
    parser = OptionParser(usage="%prog: [option] [string]")
    parser.add_option('-o', '--type', action='store_true',
                       help="-o string")
    parser.add_option('-b', '--build', action='store_true',
                      help="-b 0:word 1:action")
    (options, args) = parser.parse_args()

    if not (len(args) == 1):
        parser.print_help()
        sys.exit(1)

    if options.type:
        print calculate(read_dict(args[0]), 10)
    elif options.build:
        build
        print "I'm building"

if __name__ == '__main__':
    main()
