# -*- coding: utf-8 -*-
from __future__ import print_function
from collections import Counter
import yt.wrapper as yt
import datetime
from sklearn.externals import joblib
from itertools import izip
import random


from itertools import izip
from sklearn.externals.joblib import Parallel, delayed
import multiprocessing
import json
from itertools import izip
import pandas as pd

import requests



yt.config.set_proxy("hahn")
data_dir = "//projects/scoring/raiff/XPROD-948"
if not yt.exists(data_dir):
    yt.mkdir(data_dir)
yt_tmp_dir = "//projects/scoring/tmp-partners-data/ycscraiffeisen1"
if not yt.exists(yt_tmp_dir):
    yt.mkdir(yt_tmp_dir)

df = pd.read_csv("./yandex-100k.csv", sep=";")
print (df.shape)
# df = df.iloc[df.target.values!=-1, :]
# print (df.shape)

df.email.fillna("", inplace=True)
df.phone = df.phone.astype(str)

score_name = 'mkb_xprod_960_m5'

recs = []
counter = 0
for ph, email in izip(df.phone, df.email):
    if email!="":
        s = 'curl -w \'HTTP_CODE:%{response_code}\\n\' -X GET --data \'{"user_ids": {"phones": [{"phone":"'+ph+'"}], "emails": [{"email":"'+email+'"}]}, "scores":[{"score_name":"'+score_name+'"}]}\' -H "Content-Type: application/json" -H "Authorization: 5q5iDSyt38toAnP0e6XKcLGLwcVPY3MIfd9A6afXtsucBj8mVNylwX91SF5xVlKu9FjRzXlA4Ws" https://datacloud.yandex.net/v1/accounts/mkb/scores'
    else:
        s = 'curl -w \'HTTP_CODE:%{response_code}\\n\' -X GET --data \'{"user_ids": {"phones": [{"phone":"'+ph+'"}]}, "scores":[{"score_name":"'+score_name+'"}]}\' -H "Content-Type: application/json" -H "Authorization: 5q5iDSyt38toAnP0e6XKcLGLwcVPY3MIfd9A6afXtsucBj8mVNylwX91SF5xVlKu9FjRzXlA4Ws" https://datacloud.yandex.net/v1/accounts/mkb/scores'
    break
print (s)

rec2request = []
counter = 0
for ph, email in izip(df.phone, df.email):
    rec2request.append((ph.split('.')[0], email))
    counter += 1
    # if counter>4000:
    #    break
print (len(rec2request))


def processInput(ph, email):
    res = None
    headers = {
        "Authorization": '5q5iDSyt38toAnP0e6XKcLGLwcVPY3MIfd9A6afXtsucBj8mVNylwX91SF5xVlKu9FjRzXlA4Ws',
    }
    url = 'https://datacloud.yandex.net/v1/accounts/mkb/scores'

    score_name = 'mkb_xprod_960_m5' if random.random() > 0.5 else 'mkb_xprod_960_m1'
    if ph == "nan":
        return -2
    try:
        if email:
            payload = {"user_ids": {"phones": [{"phone": ph}], "emails": [{"email": email}]}, "scores": [{"score_name": score_name}]}
        else:
            payload = {"user_ids": {"phones": [{"phone": ph}]}, "scores": [{"score_name": score_name}]}
        status_code = requests.post(url, json=payload, headers=headers).status_code
    except Exception as ex:
        print(ex)
        status_code = -1

    if status_code != 200:
        print(status_code, payload)
    return status_code


num_cores = 16
print('N threads: {}'.format(num_cores))

for i in range(10):
    results = Parallel(n_jobs=num_cores, verbose=2)(delayed(processInput)(ph, email) for ph, email in rec2request)
    res = {}
    for num in results:
        if num in res:
            res[num] += 1
        else:
            res[num] = 1

    print(res)
# {'user_ids': {'phones': [{'phone': '9257777778.0'}],'scores': [{'score_name': 'mkb_xprod_960_m1'}]}}
# {"user_ids":{"phones": [{"phone":"79104783008"}]}, "scores":[{"score_name":"mkb_xprod_960_m5"}, {"score_name":"mkb_xprod_960_m3"}]}

