import json

import requests
from transliterate import translit

_eng_chars = "~!@#$%^&qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>?"
_rus_chars = "ё!\"№;%:?йцукенгшщзхъфывапролджэячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"
_trans_table = dict(zip(_eng_chars, _rus_chars))


def _fix_layout(s):
    return "".join([_trans_table.get(c, c) for c in s])


def es_predict(es_url, keywords):
    query = set(
        keywords +
        [_fix_layout(word) for word in keywords] +
        [translit(word, "ru") for word in keywords]
    )

    post_data = json.dumps({
        "size": 5,
        "query": {
            "simple_query_string": {
                "query": "|".join(query),
                "flags": "OR|PREFIX"
            }
        }
    })
    response = requests.post(es_url + "/_search", data=post_data).json()

    if "hits" in response and "hits" in response["hits"]:
        for it in response["hits"]["hits"]:
            if "_source" in it and "query" in it["_source"]:
                yi
eld it["_source"]["query"]
