import json
import requests
from pathlib import Path
from YQ_OCR.configs.config import *


# 发送请求 带正确答案参数
def send_request(img_path: Path, img_json: str):
    file = {'file': (img_path.name, open(img_path, 'rb'), img_path)}
    payload = {'docDataStr': img_json}
    r = requests.post(url + url_path, files=file, data=payload)
    return r.json()


# 编辑距离
def Levenshtein_Distance(str1, str2):
    matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
    for i in range(1, len(str1) + 1):
        for j in range(1, len(str2) + 1):
            d = 0 if (str1[i - 1] == str2[j - 1]) else 1
            matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d)
    return matrix[len(str1)][len(str2)]


# 处理返回结果
def parse_result(r):  # sourcery skip: dict-comprehension
    if r['status'] == '000':
        result = r['result']
        res = {}
        for field in keyDict:
            if field in result:
                res[field] = result[field]
        res['noKeyList'] = result['noKeyList']
        res['logoList'] = result['logoList']
        res['tableList'] = result['tableList']
        logoFileName = [log['logoFileName'] for log in res['logoList']]
        res['logoList'] = logoFileName
        return res
    elif r['status'] == '101':
        return "101"


# 打开正确的json文件
def open_true_json(j_path):
    with j_path.open('r', encoding='utf-8') as f:
        j_dict = json.load(f)
        j_json_str = json.dumps(j_dict, ensure_ascii=False)
        return j_dict, j_json_str
